<?php
include 'config.php';

// Ensure $pdo is defined and connected
if (!isset($pdo)) {
    try {
        $pdo = new PDO('mysql:host=localhost;dbname=your_database_name', 'your_username', 'your_password');
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        die("Database connection failed: " . $e->getMessage());
    }
}

// Handle adding or updating a customer
if (isset($_GET['customer_search'])) {
    $search_term = trim($_GET['customer_search']);
    $search_query = "SELECT id, name, mobile FROM contacts WHERE name LIKE :search OR mobile LIKE :search";
    $stmt = $pdo->prepare($search_query);
    $stmt->execute([':search' => "%$search_term%"]);
    $search_results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Return JSON response for live search
    header('Content-Type: application/json');
    echo json_encode($search_results);
    exit;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_customer'])) {
    $customer_name = trim($_POST['customer_name']);
    $customer_mobile = trim($_POST['customer_mobile']);

    if (!empty($customer_name) && !empty($customer_mobile)) {
        // Check if the customer already exists
        $check_query = "SELECT * FROM contacts WHERE mobile = :mobile";
        $stmt = $pdo->prepare($check_query);
        $stmt->execute([':mobile' => $customer_mobile]);
        $existing_customer = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($existing_customer) {
            // Update customer if exists
            $update_query = "UPDATE contacts SET name = :name WHERE mobile = :mobile";
            $stmt = $pdo->prepare($update_query);
            $stmt->execute([':name' => $customer_name, ':mobile' => $customer_mobile]);
        } else {
            // Insert new customer
            $insert_query = "INSERT INTO contacts (name, mobile) VALUES (:name, :mobile)";
            $stmt = $pdo->prepare($insert_query);
            $stmt->execute([':name' => $customer_name, ':mobile' => $customer_mobile]);
        }
    }
}

// Handle live search for customers
if (isset($_GET['customer_search'])) {
    $search_term = trim($_GET['customer_search']);
    $search_query = "SELECT id, name, mobile FROM contacts WHERE name LIKE :search OR mobile LIKE :search";
    $stmt = $pdo->prepare($search_query);
    $stmt->execute([':search' => "%$search_term%"]);
    $search_results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Return JSON response for live search
    header('Content-Type: application/json');
    echo json_encode($search_results);
    exit;
}

// Handle adding a new job
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_job'])) {
    // Collect form data
    $customer_id = $_POST['customer_id'];  // Use customer ID from the contacts table
    $phone_model = $_POST['phone_model'];
    $phone_problem = $_POST['phone_problem'];
    $repair_status = $_POST['repair_status'];
    $price = $_POST['price'];

    // Fetch customer info using customer_id
    $customer_query = "SELECT * FROM contacts WHERE id = :customer_id";
    $stmt = $pdo->prepare($customer_query);
    $stmt->execute([':customer_id' => $customer_id]);
    $customer = $stmt->fetch(PDO::FETCH_ASSOC);

    // Insert job sheet into the database
    $query = "INSERT INTO repairs (customer_name, customer_phone, phone_model, phone_problem, repair_status, price) 
              VALUES (:customer_name, :customer_phone, :phone_model, :phone_problem, :repair_status, :price)";
    $stmt = $pdo->prepare($query);
    $stmt->execute([
        ':customer_name' => $customer['name'],
        ':customer_phone' => $customer['mobile'],
        ':phone_model' => $phone_model,
        ':phone_problem' => $phone_problem,
        ':repair_status' => $repair_status,
        ':price' => $price,
    ]);
}

// Handle delete request
if (isset($_GET['delete_id'])) {
    $delete_id = $_GET['delete_id'];
    $query = "DELETE FROM repairs WHERE id = :id";
    $stmt = $pdo->prepare($query);
    $stmt->execute([':id' => $delete_id]);
}

// Handle delivery request (mark as Delivered)
if (isset($_GET['deliver_id'])) {
    $deliver_id = $_GET['deliver_id'];
    $query = "UPDATE repairs SET repair_status = 'Delivered' WHERE id = :id";
    $stmt = $pdo->prepare($query);
    $stmt->execute([':id' => $deliver_id]);
}

// Handle search
$search = '';
if (isset($_GET['search'])) {
    $search = $_GET['search'];
}

$query = "SELECT * FROM repairs WHERE 
          id LIKE :search OR 
          customer_name LIKE :search OR 
          customer_phone LIKE :search 
          ORDER BY created_at DESC";
$stmt = $pdo->prepare($query);
$stmt->execute([':search' => "%$search%"]);
$repairs = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch all customers for the dropdown
$customers_query = "SELECT * FROM contacts";
$customers_stmt = $pdo->prepare($customers_query);
$customers_stmt->execute();
$customers = $customers_stmt->fetchAll(PDO::FETCH_ASSOC);
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Repair Job Sheet</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        .status-pending {
            background-color: yellow;
        }
        .status-in-progress {
            background-color: orange;
        }
        .status-completed {
            background-color: green;
            color: white;
        }
        .status-delivered {
            background-color: blue;
            color: white;
        }
    </style>
</head>
<body class="bg-gray-100">

    <div class="container mx-auto p-4">

        <!-- Job Sheet Form -->
        <h1 class="text-3xl font-semibold mb-4 text-center">Add Job Sheet</h1>
        <form method="POST" action="index.php" class="bg-white p-6 rounded-lg shadow-lg mb-4">
            <!-- Select Customer or Add New -->
            <label for="customer_id" class="block text-sm font-medium">Customer</label>
            <select name="customer_id" id="customer_id" class="block w-full p-2 border rounded mb-4" required>
                <option value="">-- Select Existing Customer --</option>
                <?php foreach ($customers as $customer): ?>
                    <option value="<?php echo $customer['id']; ?>"><?php echo $customer['name'] . ' - ' . $customer['mobile']; ?></option>
                <?php endforeach; ?>
            </select>
            <button type="button" onclick="openModal()" id="addCustomerButton" class="bg-green-500 text-white py-2 px-4 rounded mb-4">Add New Customer</button>

            <!-- Phone model input -->
            <label for="model" class="block text-sm font-medium">Phone Model</label>
            <input type="text" name="phone_model" id="phone_model" class="block w-full p-2 border rounded mb-4" required>
            
            <label for="phone_problem" class="block text-sm font-medium">Phone Problem</label>
            <select name="phone_problem" id="phone_problem" class="block w-full p-2 border rounded mb-4" required>
                <option value="No Power">No Power</option>
                <option value="Repair">Repair</option>
                <option value="Screen Damage">Screen Damage</option>
                <option value="Battery Issue">Battery Issue</option>
                <option value="Water Damage">Water Damage</option>
                <option value="Speaker Not Working">Speaker Not Working</option>
                <option value="Microphone Issue">Microphone Issue</option>
                <option value="Charging Port Issue">Charging Port Issue</option>
                <option value="Software Issue">Software Issue</option>
                <option value="Camera Not Working">Camera Not Working</option>
                <option value="Overheating">Overheating</option>
                <option value="Network Issue">Network Issue</option>
            </select>
            
            <label for="repair_status" class="block text-sm font-medium">Repair Status</label>
            <select name="repair_status" id="repair_status" class="block w-full p-2 border rounded mb-4" required>
                <option value="Pending">Pending</option>
                <option value="In Progress">In Progress</option>
                <option value="Completed">Completed</option>
            </select>

            <label for="price" class="block text-sm font-medium">Price ($)</label>
            <input type="number" name="price" id="price" class="block w-full p-2 border rounded mb-4" required>

            <button type="submit" name="add_job" class="bg-blue-500 text-white py-2 px-4 rounded">Add Job Sheet</button>
        </form>

        <!-- Modal for Adding New Customer -->
        <div id="customerModal" class="fixed top-0 left-0 right-0 bottom-0 bg-black bg-opacity-50 hidden">
            <div class="relative w-1/3 mx-auto bg-white p-4 rounded-lg shadow-lg">
            <h2 class="text-xl font-semibold mb-4">Add New Customer</h2>
            <form method="POST" action="index.php" onsubmit="addCustomer(event)">
                <label for="name" class="block text-sm font-medium">Customer Name</label>
                <input type="text" name="name" id="new_customer_name" class="block w-full p-2 border rounded mb-4" required>

                <label for="mobile" class="block text-sm font-medium">Customer Mobile</label>
                <input type="text" name="mobile" id="new_customer_mobile" class="block w-full p-2 border rounded mb-4" pattern="[0-9]{10}" title="Enter a valid 10-digit mobile number" required>

                <button type="submit" class="bg-green-500 text-white py-2 px-4 rounded">Add Customer</button>
            </form>
            <button type="button" onclick="closeModal()" class="text-red-500 hover:underline mt-4">Cancel</button>
            </div>
        </div>

        <script>
            async function addCustomer(event) {
            event.preventDefault();
            const name = document.getElementById('new_customer_name').value;
            const mobile = document.getElementById('new_customer_mobile').value;

            const response = await fetch('index.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                add_customer: true,
                customer_name: name,
                customer_mobile: mobile
                })
            });

            if (response.ok) {
                const newCustomer = { name, mobile }; // Simulate response
                const customerSelect = document.getElementById('customer_id');
                const option = document.createElement('option');
                option.value = newCustomer.id || 'new'; // Replace 'new' with actual ID if available
                option.textContent = `${newCustomer.name} - ${newCustomer.mobile}`;
                customerSelect.appendChild(option);
                customerSelect.value = option.value;
                closeModal();
            } else {
                alert('Failed to add customer. Please try again.');
            }
            }
        </script>

        <!-- Repair Table -->
        <h2 class="text-2xl font-semibold mb-4">Repairs List</h2>
        <table class="min-w-full bg-white border border-gray-300 shadow-lg rounded-lg">
            <thead>
                <tr>
                    <th class="py-2 px-4 border-b">ID</th>
                    <th class="py-2 px-4 border-b">Customer</th>
                    <th class="py-2 px-4 border-b">Phone Model</th>
                    <th class="py-2 px-4 border-b">Problem</th>
                    <th class="py-2 px-4 border-b">Status</th>
                    <th class="py-2 px-4 border-b">Price</th>
                    <th class="py-2 px-4 border-b">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($repairs as $repair): ?>
                    <tr>
                        <td class="py-2 px-4 border-b"><?php echo $repair['id']; ?></td>
                        <td class="py-2 px-4 border-b"><?php echo $repair['customer_name'] . ' - ' . $repair['customer_phone']; ?></td>
                        <td class="py-2 px-4 border-b"><?php echo $repair['phone_model']; ?></td>
                        <td class="py-2 px-4 border-b"><?php echo $repair['phone_problem']; ?></td>
                        <td class="py-2 px-4 border-b <?php echo 'status-' . strtolower(str_replace(' ', '-', $repair['repair_status'])); ?>"><?php echo $repair['repair_status']; ?></td>
                        <td class="py-2 px-4 border-b"><?php echo '$' . number_format($repair['price'], 2); ?></td>
                        <td class="py-2 px-4 border-b">
                            <a href="index.php?delete_id=<?php echo $repair['id']; ?>" class="text-red-500 hover:underline">Delete</a>
                            <?php if ($repair['repair_status'] != 'Delivered'): ?>
                                <a href="index.php?deliver_id=<?php echo $repair['id']; ?>" class="text-blue-500 hover:underline ml-4">Mark as Delivered</a>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

    </div>

    <script>
        function closeModal() {
            document.getElementById("customerModal").style.display = "none";
        }
        function openModal() {
            document.getElementById("customerModal").style.display = "block";
        }
    </script>

</body>
</html>
