<?php
// PHP code to handle form data for editing a product

$servername = "localhost";
$username = "wintelsoft_vinod";
$password = "vinodbhaskar69*";
$dbname = "wintelsoft_svf";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$success_message = "";
$error_message = "";
$product = null;

// Function to handle image upload, validation, and renaming
function handleImageUpload($file, $product_code, $index) {
    global $error_message;
    
    // Check if a file was uploaded for this field
    if (empty($file["tmp_name"])) {
        return null;
    }

    $imageFileType = strtolower(pathinfo(basename($file["name"]), PATHINFO_EXTENSION));
    
    // Check if file is an actual image
    $check = getimagesize($file["tmp_name"]);
    if ($check === false) {
        $error_message = "File is not a valid image.";
        return false;
    }

    // Check file size
    if ($file["size"] > 500000) {
        $error_message = "Sorry, your file is too large. (Max 500 KB)";
        return false;
    }

    // Allow certain file formats
    if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
        $error_message = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        return false;
    }

    // Generate new unique filename
    $new_file_name = $product_code . "_" . $index . "." . $imageFileType;
    $target_dir = "uploads/";
    $target_file = $target_dir . $new_file_name;

    if (move_uploaded_file($file["tmp_name"], $target_file)) {
        return $new_file_name;
    } else {
        $error_message = "Sorry, there was an error uploading your file.";
        return false;
    }
}


// Check if a product ID is provided for editing
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $id = (int)$_GET['id'];
    
    // Use a prepared statement to prevent SQL injection and retrieve the new salesman column
    $stmt = $conn->prepare("SELECT id, product_code, date_of_order, item_description, measurements_and_specification, type_of_wood, quantity, scheduled_date_of_delivery, despatched_status, product_image, product_image2, product_image3, customer_name, address, mobile_no, salesman FROM products WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $product = $result->fetch_assoc();
    } else {
        $error_message = "No product found with this ID.";
    }
    $stmt->close();
}

// Handle form submission for update
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize and get form data
    $id = (int)$_POST['id'];
    $product_code = trim($_POST['product_code']);
    $date_of_order = $_POST['date_of_order'];
    $item_description = $_POST['item_description'];
    $measurements_and_specification = $_POST['measurements_and_specification'];
    $type_of_wood = $_POST['type_of_wood'];
    $quantity = (int)$_POST['quantity'];
    $scheduled_date_of_delivery = $_POST['scheduled_date_of_delivery'];
    $despatched_status = $_POST['despatched_status'];
    $customer_name = trim($_POST['customer_name']);
    $address = trim($_POST['address']);
    $mobile_no = trim($_POST['mobile_no']);
    // --- NEW: Retrieve the salesman data ---
    $salesman = trim($_POST['salesman']);

    // Check for duplicate product code on other products
    $sql_check_code = "SELECT id FROM products WHERE product_code = ? AND id != ?";
    $stmt_check = $conn->prepare($sql_check_code);
    $stmt_check->bind_param("si", $product_code, $id);
    $stmt_check->execute();
    $result_check = $stmt_check->get_result();
    
    if ($result_check->num_rows > 0) {
        $error_message = "Error: A product with this code already exists.";
    } else {
        // Handle image uploads
        $image_name1 = $_POST['existing_product_image'];
        $image_name2 = $_POST['existing_product_image2'];
        $image_name3 = $_POST['existing_product_image3'];

        $new_image1 = handleImageUpload($_FILES['product_image'], $product_code, 1);
        $new_image2 = handleImageUpload($_FILES['product_image2'], $product_code, 2);
        $new_image3 = handleImageUpload($_FILES['product_image3'], $product_code, 3);
        
        // Update filenames if new images were uploaded successfully
        if ($new_image1 !== null && $new_image1 !== false) $image_name1 = $new_image1;
        if ($new_image2 !== null && $new_image2 !== false) $image_name2 = $new_image2;
        if ($new_image3 !== null && $new_image3 !== false) $image_name3 = $new_image3;
        
        // Only proceed with database update if there were no image upload errors
        if ($error_message === "") {
            $stmt_check->close();

            // --- MODIFIED: Update SQL to include salesman column ---
            $sql_update = "UPDATE products SET product_code=?, date_of_order=?, item_description=?, measurements_and_specification=?, type_of_wood=?, quantity=?, scheduled_date_of_delivery=?, despatched_status=?, product_image=?, product_image2=?, product_image3=?, customer_name=?, address=?, mobile_no=?, salesman=? WHERE id=?";
            $stmt = $conn->prepare($sql_update);
            
            // --- MODIFIED: Bind salesman (s) and shift id to the end ---
            // Binding types: sssss i sssssssss i (15 strings, 1 integer for quantity, 1 integer for id)
            $stmt->bind_param("sssssisssssssssi", 
                $product_code, $date_of_order, $item_description, $measurements_and_specification, 
                $type_of_wood, $quantity, $scheduled_date_of_delivery, $despatched_status, 
                $image_name1, $image_name2, $image_name3, $customer_name, $address, $mobile_no, 
                $salesman, // NEW PARAMETER
                $id
            );

            if ($stmt->execute()) {
                // Redirect to the products list page after a successful update
                header("Location: view_products.php");
                exit; // Make sure no other code is executed
            } else {
                $error_message = "Error updating record: " . $stmt->error;
            }
            $stmt->close();
        }
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Product</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');

        body {
            font-family: 'Roboto', sans-serif;
            background-color: #f0f2f5;
            color: #333;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 40px auto;
            background-color: #ffffff;
            padding: 40px;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        }

        h2 {
            text-align: center;
            color: #ffffff;
            background-color: #3498db;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 30px;
            font-weight: 700;
            letter-spacing: 1px;
        }

        .alert-message {
            text-align: center;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 8px;
            font-weight: bold;
        }
        .alert-error {
            background-color: #e74c3c;
            color: white;
        }
        .alert-success {
            background-color: #2ecc71;
            color: white;
        }

        .form-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }

        .form-table td {
            padding: 15px;
            vertical-align: top;
        }

        .form-table td:first-child {
            width: 30%;
            text-align: right;
            font-weight: bold;
            padding-right: 20px;
            color: #555;
        }

        .form-table input[type="text"],
        .form-table input[type="date"],
        .form-table input[type="number"],
        .form-table textarea,
        .form-table input[type="file"],
        .form-table select {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 8px;
            box-sizing: border-box;
            font-size: 16px;
            transition: border-color 0.3s, box-shadow 0.3s;
        }

        .form-table textarea {
            resize: vertical;
            min-height: 100px;
        }

        .form-table input:focus,
        .form-table textarea:focus,
        .form-table select:focus {
            border-color: #3498db;
            box-shadow: 0 0 8px rgba(52, 152, 219, 0.2);
            outline: none;
        }
        
        .submit-container {
            text-align: center;
            padding-top: 20px;
        }

        input[type="submit"] {
            background-color: #2ecc71;
            color: white;
            padding: 15px 30px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 18px;
            font-weight: bold;
            transition: background-color 0.3s, transform 0.2s;
        }

        input[type="submit"]:hover {
            background-color: #27ae60;
            transform: translateY(-2px);
        }

        .view-link {
            display: block;
            text-align: center;
            margin-top: 20px;
        }

        .view-link a {
            color: #3498db;
            text-decoration: none;
            font-weight: bold;
        }

        .view-link a:hover {
            text-decoration: underline;
        }

        .image-preview {
            max-width: 150px;
            max-height: 150px;
            margin-top: 10px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        /* Responsive design */
        @media (max-width: 600px) {
            .form-table td {
                display: block;
                width: 100%;
                text-align: left !important;
                padding: 10px 0;
            }
            .form-table td:first-child {
                padding-right: 0;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>Edit Product</h2>

        <?php if ($success_message): ?>
            <div class="alert-message alert-success"><?php echo $success_message; ?></div>
        <?php endif; ?>
        <?php if ($error_message): ?>
            <div class="alert-message alert-error"><?php echo $error_message; ?></div>
        <?php endif; ?>

        <?php if ($product): ?>
            <form id="productForm" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) . '?id=' . htmlspecialchars($product['id']);?>" method="post" enctype="multipart/form-data">
                <input type="hidden" name="id" value="<?php echo htmlspecialchars($product['id']); ?>">
                <input type="hidden" name="existing_product_image" value="<?php echo htmlspecialchars($product['product_image']); ?>">
                <input type="hidden" name="existing_product_image2" value="<?php echo htmlspecialchars($product['product_image2']); ?>">
                <input type="hidden" name="existing_product_image3" value="<?php echo htmlspecialchars($product['product_image3']); ?>">
                
                <table class="form-table">
                    <tr>
                        <td><label for="product_code">Product Code:</label></td>
                        <td><input type="text" id="product_code" name="product_code" value="<?php echo htmlspecialchars($product['product_code']); ?>" required></td>
                    </tr>
                    <tr>
                        <td><label for="date_of_order">Date of Order:</label></td>
                        <td><input type="date" id="date_of_order" name="date_of_order" value="<?php echo htmlspecialchars($product['date_of_order']); ?>" required></td>
                    </tr>
                    <tr>
                        <td><label for="customer_name">Customer Name:</label></td>
                        <td><input type="text" id="customer_name" name="customer_name" value="<?php echo htmlspecialchars($product['customer_name']); ?>" required></td>
                    </tr>
                    <tr>
                        <td><label for="address">Address:</label></td>
                        <td><textarea id="address" name="address" required><?php echo htmlspecialchars($product['address']); ?></textarea></td>
                    </tr>
                    <tr>
                        <td><label for="mobile_no">Mobile No:</label></td>
                        <td><input type="tel" id="mobile_no" name="mobile_no" pattern="[0-9]{10}" value="<?php echo htmlspecialchars($product['mobile_no']); ?>" required></td>
                    </tr>
                    <!-- --- NEW: Salesman Field Added --- -->
                    <tr>
                        <td><label for="salesman">Salesman:</label></td>
                        <td><input type="text" id="salesman" name="salesman" value="<?php echo htmlspecialchars($product['salesman'] ?? ''); ?>" required></td>
                    </tr>
                    <!-- --- END NEW FIELD --- -->
                    <tr>
                        <td><label for="item_description">Item Description:</label></td>
                        <td><textarea id="item_description" name="item_description" required><?php echo htmlspecialchars($product['item_description']); ?></textarea></td>
                    </tr>
                    <tr>
                        <td><label for="measurements_and_specification">Measurements & Specification:</label></td>
                        <td><textarea id="measurements_and_specification" name="measurements_and_specification" required><?php echo htmlspecialchars($product['measurements_and_specification']); ?></textarea></td>
                    </tr>
                    <tr>
                        <td><label for="type_of_wood">Type of Wood:</label></td>
                        <td><input type="text" id="type_of_wood" name="type_of_wood" value="<?php echo htmlspecialchars($product['type_of_wood']); ?>" required></td>
                    </tr>
                    <tr>
                        <td><label for="quantity">Quantity:</label></td>
                        <td><input type="number" id="quantity" name="quantity" value="<?php echo htmlspecialchars($product['quantity']); ?>" required></td>
                    </tr>
                    <tr>
                        <td><label for="scheduled_date_of_delivery">Scheduled Date of Delivery:</label></td>
                        <td><input type="date" id="scheduled_date_of_delivery" name="scheduled_date_of_delivery" value="<?php echo htmlspecialchars($product['scheduled_date_of_delivery']); ?>" required></td>
                    </tr>
                    <tr>
                        <td><label for="despatched_status">Despatched Status:</label></td>
                        <td>
                            <select id="despatched_status" name="despatched_status" required>
                                <option value="No" <?php echo ($product['despatched_status'] == 'No') ? 'selected' : ''; ?>>No</option>
                                <option value="Yes" <?php echo ($product['despatched_status'] == 'Yes') ? 'selected' : ''; ?>>Yes</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td><label for="product_image">Product Image 1:</label></td>
                        <td>
                            <input type="file" id="product_image" name="product_image" accept="image/*">
                            <?php if (!empty($product['product_image'])): ?>
                                <br><span>Current Image:</span><br>
                                <img src="uploads/<?php echo htmlspecialchars($product['product_image']); ?>" alt="Product Image 1" class="image-preview">
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <td><label for="product_image2">Product Image 2:</label></td>
                        <td>
                            <input type="file" id="product_image2" name="product_image2" accept="image/*">
                            <?php if (!empty($product['product_image2'])): ?>
                                <br><span>Current Image:</span><br>
                                <img src="uploads/<?php echo htmlspecialchars($product['product_image2']); ?>" alt="Product Image 2" class="image-preview">
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <td><label for="product_image3">Product Image 3:</label></td>
                        <td>
                            <input type="file" id="product_image3" name="product_image3" accept="image/*">
                            <?php if (!empty($product['product_image3'])): ?>
                                <br><span>Current Image:</span><br>
                                <img src="uploads/<?php echo htmlspecialchars($product['product_image3']); ?>" alt="Product Image 3" class="image-preview">
                            <?php endif; ?>
                        </td>
                    </tr>
                </table>
                <div class="submit-container">
                    <input type="submit" value="Update Product">
                </div>
            </form>

            <div class="view-link">
                <a href="view_products.php">View All Products</a>
            </div>
        <?php else: ?>
            <p>Error: No product found to edit.</p>
            <div class="view-link">
                <a href="view_products.php">Back to Products</a>
            </div>
        <?php endif; ?>
    </div>
    <script>
        const form = document.getElementById('productForm');
        if (form) {
            const validationMessageDiv = document.createElement('div');
            validationMessageDiv.className = 'alert-message alert-error';
            validationMessageDiv.style.display = 'none';
            form.prepend(validationMessageDiv);

            form.addEventListener('submit', function(event) {
                const productCode = document.getElementById('product_code').value;
                const customerName = document.getElementById('customer_name').value;
                const address = document.getElementById('address').value;
                const mobileNo = document.getElementById('mobile_no').value;
                const salesman = document.getElementById('salesman').value; // Get salesman value
                const quantity = document.getElementById('quantity').value;
                
                let message = '';
                let isValid = true;

                if (productCode.trim() === '' || customerName.trim() === '' || address.trim() === '' || mobileNo.trim() === '' || salesman.trim() === '') {
                    message = 'All fields, including Salesman, are required.';
                    isValid = false;
                } else if (quantity <= 0) {
                    message = 'Quantity must be a positive number.';
                    isValid = false;
                } else if (!/^[0-9]{10}$/.test(mobileNo)) {
                    message = 'Mobile number must be a 10-digit number.';
                    isValid = false;
                }

                if (!isValid) {
                    event.preventDefault();
                    validationMessageDiv.style.display = 'block';
                    validationMessageDiv.innerHTML = message;
                } else {
                    validationMessageDiv.style.display = 'none';
                }
            });
        }
    </script>
</body>
</html>
