<?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);
}

// --- NEW LOGIC: Handle AJAX request to fetch product data ---
if (isset($_GET['fetch_code'])) {
    $code_to_fetch = $conn->real_escape_string($_GET['fetch_code']);
    
    // Select all fields including product_image
    $sql_fetch = "SELECT date_of_order, item_description, measurements_and_specification, type_of_wood, quantity, scheduled_date_of_delivery, despatched_status, customer_name, address, mobile_no, product_image FROM products WHERE product_code = '$code_to_fetch'";
    $result_fetch = $conn->query($sql_fetch);

    // 🌟 CORRECTED LINE: Check if num_rows is greater than 0 (i.e., at least one product found)
    if ($result_fetch->num_rows > 0) { 
        $data = $result_fetch->fetch_assoc();
        
        // Return JSON data
        header('Content-Type: application/json');
        echo json_encode(['status' => 'success', 'data' => $data]);
        $conn->close();
        exit();
    } else {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => 'Product not found.']);
        $conn->close();
        exit();
    }
}
// -----------------------------------------------------------


// --- EXISTING LOGIC: Fetch all product codes for the dropdown ---
$product_codes = [];
$sql_codes = "SELECT product_code FROM products ORDER BY product_code ASC";
$result_codes = $conn->query($sql_codes);

if ($result_codes->num_rows > 0) {
    while ($row = $result_codes->fetch_assoc()) {
        $product_codes[] = $row['product_code'];
    }
}
// -----------------------------------------------------------


// 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']);


    // Server-side validation
    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)) {
        $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. Please choose a unique Product Code.";
        } 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 = getimagesize($_FILES["product_image"]["tmp_name"]);
                if($check === false) {
                    $error_message = "File is not an image.";
                    $uploadOk = 0;
                }

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

                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;
                    }
                }
            } else if (isset($_POST['copied_image_name']) && !empty($_POST['copied_image_name'])) {
                // Keep the existing image name if one was copied and no new file uploaded
                $image_name = $conn->real_escape_string($_POST['copied_image_name']);
            }

            // Only proceed with database insertion if no upload errors occurred
            if ($uploadOk == 1) {
                // Prepare the SQL query
                $image_val = ($image_name === NULL) ? 'NULL' : "'$image_name'";
                
                $sql = "INSERT INTO products (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, user_id)
                        VALUES ('$product_code', '$date_of_order', '$item_description', '$measurements_and_specification', '$type_of_wood', '$quantity', '$scheduled_date_of_delivery', '$despatched_status', $image_val, '$customer_name', '$address', '$mobile_no', '$user_id')";
                
                if ($conn->query($sql) === TRUE) {
                    $success_message = "New record created successfully by duplicating content!";
                    $_POST = array(); 
                } else {
                    $error_message = "Error: " . $sql . "<br>" . $conn->error;
                }
            }
        }
    }
}

// Close the connection only if it's still open
if (isset($conn) && $conn->ping()) {
    $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;
        }
        
        .duplicate-section {
            background-color: #f7f9fc;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            border: 1px dashed #c0c0c0;
        }

        .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;
        }

        @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">
            
            <div class="duplicate-section">
                <label for="duplicate_code" style="font-weight: bold; color: #3498db;">Duplicate from Existing Product Code:</label>
                <select id="duplicate_code" name="duplicate_code" onchange="fetchProductData(this.value)">
                    <option value="">-- Select Product Code to Duplicate --</option>
                    <?php 
                    foreach ($product_codes as $code) {
                        echo "<option value=\"" . htmlspecialchars($code) . "\">" . htmlspecialchars($code) . "</option>";
                    }
                    ?>
                </select>
                <small style="display: block; margin-top: 10px; color: #7f8c8d;">Selecting a code will auto-fill the form below. Remember to enter a new, unique **Product Code**.</small>
            </div>
            
            <table class="form-table">
                <tr>
                    <td><label for="product_code">New 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>
                <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/*" >
                        <p id="current_image_note" style="margin-top: 5px; font-style: italic; color: #7f8c8d;"></p>
                        <input type="hidden" id="copied_image_name" name="copied_image_name" value="">
                    </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>
        /**
         * Function to fetch product data via AJAX and populate the form fields.
         */
        function fetchProductData(productCode) {
            if (productCode === "") {
                // Clear all fields if the default option is selected
                document.getElementById('productForm').reset();
                document.getElementById('copied_image_name').value = '';
                document.getElementById('current_image_note').innerHTML = '';
                return;
            }

            // Perform AJAX request to fetch product details
            fetch(`<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>?fetch_code=${encodeURIComponent(productCode)}`)
                .then(response => {
                    const contentType = response.headers.get("content-type");
                    if (contentType && contentType.indexOf("application/json") !== -1) {
                        return response.json();
                    } else {
                        // If it fails to parse JSON, log the text response for debugging
                        return response.text().then(text => {
                            console.error('Received non-JSON response:', text);
                            throw new Error('Received non-JSON response from server.');
                        });
                    }
                })
                .then(data => {
                    if (data.status === 'success') {
                        const product = data.data;
                        
                        document.getElementById('date_of_order').value = product.date_of_order;
                        document.getElementById('customer_name').value = product.customer_name;
                        document.getElementById('address').value = product.address;
                        document.getElementById('mobile_no').value = product.mobile_no;
                        document.getElementById('item_description').value = product.item_description;
                        document.getElementById('measurements_and_specification').value = product.measurements_and_specification;
                        document.getElementById('type_of_wood').value = product.type_of_wood;
                        document.getElementById('quantity').value = product.quantity;
                        document.getElementById('scheduled_date_of_delivery').value = product.scheduled_date_of_delivery;
                        document.getElementById('despatched_status').value = product.despatched_status;

                        // Handle the image field
                        if (product.product_image) {
                            document.getElementById('current_image_note').innerHTML = `Image to be duplicated: <strong>${product.product_image}</strong> (Upload a new file to change it)`;
                            document.getElementById('copied_image_name').value = product.product_image; // Set hidden field
                        } else {
                            document.getElementById('current_image_note').innerHTML = 'No image attached to the original product.';
                            document.getElementById('copied_image_name').value = '';
                        }
                        
                        // Clear the product code input to force the user to enter a new one
                        document.getElementById('product_code').value = ''; 
                        
                    } else {
                        alert("Error fetching product data: " + data.message);
                    }
                })
                .catch(error => {
                    console.error('Fetch error:', error);
                    alert("An error occurred while fetching product data. Please check the browser console for details.");
                });
        }


        // Existing form validation script (kept for completeness)
        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;
            const quantity = document.getElementById('quantity').value;
            
            let message = '';
            let isValid = true;

            if (productCode.trim() === '' || customerName.trim() === '' || address.trim() === '' || mobileNo.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>