<?php
session_start();

// Check if the user ID is set in the session. If not, the user is not logged in.
if (!isset($_SESSION['user_id'])) {
    // Redirect to the login page
    header("Location: login.php");
    exit();
}

// Get the user ID from the session
$user_id = $_SESSION['user_id'];

// PHP code to handle form submission and database insertion

$servername = "localhost"; // e.g., "localhost" or your database host
$username = "wintelsoft_vinod"; // e.g., "root"
$password = "vinodbhaskar69*"; // e.g., "" (empty for no password)
$dbname = "wintelsoft_svf"; // e.g., "company_db"

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

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

// Variables to hold messages
$error_message = "";
$success_message = "";

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Sanitize and get form data
    $product_code = $conn->real_escape_string($_POST['product_code']);
    $date_of_order = $conn->real_escape_string($_POST['date_of_order']);
    $item_description = $conn->real_escape_string($_POST['item_description']);
    $measurements_and_specification = $conn->real_escape_string($_POST['measurements_and_specification']);
    $type_of_wood = $conn->real_escape_string($_POST['type_of_wood']);
    $quantity = (int)$_POST['quantity'];
    $scheduled_date_of_delivery = $conn->real_escape_string($_POST['scheduled_date_of_delivery']);
    $despatched_status = $conn->real_escape_string($_POST['despatched_status']);
    $customer_name = $conn->real_escape_string($_POST['customer_name']);
    $address = $conn->real_escape_string($_POST['address']);
    $mobile_no = $conn->real_escape_string($_POST['mobile_no']);
    // --- NEW FIELD ADDED ---
    $salesman = $conn->real_escape_string($_POST['salesman']);
    // -----------------------


    // Server-side validation
    // --- ADDED $salesman to validation check ---
    if (empty($product_code) || empty($date_of_order) || empty($item_description) || empty($measurements_and_specification) || empty($type_of_wood) || empty($quantity) || empty($scheduled_date_of_delivery) || empty($despatched_status) || empty($customer_name) || empty($address) || empty($mobile_no) || empty($salesman)) {
        $error_message = "All fields are required.";
    } elseif ($quantity <= 0) {
        $error_message = "Quantity must be a positive number.";
    } else {
        // Check for duplicate product code
        $sql_check_code = "SELECT product_code FROM products WHERE product_code = '$product_code'";
        $result_check_code = $conn->query($sql_check_code);

        if ($result_check_code->num_rows > 0) {
            $error_message = "Error: A product with this code already exists.";
        } else {
            // Handle image upload conditionally
            $image_name = NULL; // Default to NULL if no image is uploaded
            $uploadOk = 1;

            if (isset($_FILES["product_image"]) && $_FILES["product_image"]["error"] == UPLOAD_ERR_OK) {
                $target_dir = "uploads/";
                $image_name = basename($_FILES["product_image"]["name"]);
                $target_file = $target_dir . $image_name;
                $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

                // Check if image file is a real image
                $check = getimagesize($_FILES["product_image"]["tmp_name"]);
                if($check === false) {
                    $error_message = "File is not an image.";
                    $uploadOk = 0;
                }

                // Check file size
                if ($_FILES["product_image"]["size"] > 500000) {
                    $error_message = "Sorry, your file is too large.";
                    $uploadOk = 0;
                }

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

                if ($uploadOk == 1) {
                    if (!move_uploaded_file($_FILES["product_image"]["tmp_name"], $target_file)) {
                        $error_message = "Sorry, there was an error uploading your file.";
                        $uploadOk = 0;
                    }
                }
            }

            // Only proceed with database insertion if no upload errors occurred
            if ($uploadOk == 1) {
                // Prepare the SQL query
                // --- UPDATED SQL TO INCLUDE 'salesman' COLUMN AND VALUE ---
                $columns = "product_code, date_of_order, item_description, measurements_and_specification, type_of_wood, quantity, scheduled_date_of_delivery, despatched_status, product_image, customer_name, address, mobile_no, salesman, user_id";
                $base_values = "'$product_code', '$date_of_order', '$item_description', '$measurements_and_specification', '$type_of_wood', '$quantity', '$scheduled_date_of_delivery', '$despatched_status', ";
                $end_values = ", '$customer_name', '$address', '$mobile_no', '$salesman', '$user_id'";
                
                if ($image_name === NULL) {
                    $sql = "INSERT INTO products ({$columns})
                    VALUES ({$base_values} NULL {$end_values})";
                } else {
                    $sql = "INSERT INTO products ({$columns})
                    VALUES ({$base_values} '$image_name' {$end_values})";
                }
                // -------------------------------------------------------------
                
                if ($conn->query($sql) === TRUE) {
                    $success_message = "New record created successfully!";
                } else {
                    $error_message = "Error: " . $sql . "<br>" . $conn->error;
                }
            }
        }
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product Order Form</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;
        }

        /* 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>Product Order Form</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; ?>

        <form id="productForm" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data">
            <table class="form-table">
                <tr>
                    <td><label for="product_code">Product Code:</label></td>
                    <td><input type="text" id="product_code" name="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" required></td>
                </tr>
                <tr>
                    <td><label for="customer_name">Customer Name:</label></td>
                    <td><input type="text" id="customer_name" name="customer_name" required></td>
                </tr>
                <tr>
                    <td><label for="address">Address:</label></td>
                    <td><textarea id="address" name="address" required></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}" required></td>
                </tr>
                <!-- --- NEW FIELD ADDED HERE --- -->
                <tr>
                    <td><label for="salesman">Salesman Name:</label></td>
                    <td><input type="text" id="salesman" name="salesman" required></td>
                </tr>
                <!-- ------------------------------ -->
                <tr>
                    <td><label for="item_description">Item Description:</label></td>
                    <td><textarea id="item_description" name="item_description" required></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></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" required></td>
                </tr>
                <tr>
                    <td><label for="quantity">Quantity:</label></td>
                    <td><input type="number" id="quantity" name="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" 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">No</option>
                            <option value="Yes">Yes</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td><label for="product_image">Product Image:</label></td>
                    <td><input type="file" id="product_image" name="product_image" accept="image/*" ></td>
                </tr>
            </table>
            <div class="submit-container">
                <input type="submit" value="Submit Order">
            </div>
        </form>

        <div class="view-link">
            <a href="view_products.php">View All Products</a>
        </div>
    </div>

    <script>
        const form = document.getElementById('productForm');
        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;
            // --- NEW FIELD ADDED TO JS VALIDATION ---
            const salesman = document.getElementById('salesman').value;
            // ----------------------------------------
            const quantity = document.getElementById('quantity').value;
            
            let message = '';
            let isValid = true;

            // --- UPDATED JS VALIDATION TO CHECK salesman FIELD ---
            if (productCode.trim() === '' || customerName.trim() === '' || address.trim() === '' || mobileNo.trim() === '' || salesman.trim() === '') {
                message = 'All fields 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>
