<?php
// --- PHP Backend Logic ---
// This script allows a user to edit or delete an existing daily process record.

// Start the session to enable session variable usage
session_start();

// Check if the user is logged in.
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}
$user_id = $_SESSION['user_id'];
$user_rights = ''; // Initialize user rights variable

// Configuration variables for your database connection.
$servername = "localhost";
$username = "wintelsoft_vinod";
$password = "vinodbhaskar69*";
$dbname = "wintelsoft_svf";

// Initialize variables
$record_id = "";
$product_code = "";
$message = "";
$is_success = false;

// Connect to database
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Fetch user rights from the database
$stmt_rights = $conn->prepare("SELECT user_rights FROM users WHERE user_id = ?");
if ($stmt_rights) {
    $stmt_rights->bind_param("s", $user_id);
    $stmt_rights->execute();
    $result_rights = $stmt_rights->get_result();
    if ($result_rights->num_rows > 0) {
        $row_rights = $result_rights->fetch_assoc();
        $user_rights = $row_rights['user_rights'];
    }
    $stmt_rights->close();
}

// Check for record ID and product code in URL
if (!isset($_GET['id']) || !isset($_GET['product_code'])) {
    $message = "Error: Missing record ID or product code.";
    $is_success = false;
} else {
    $record_id = $conn->real_escape_string($_GET['id']);
    $product_code = $conn->real_escape_string($_GET['product_code']);
}

// --- NEW FUNCTION TO RE-FETCH THE RECORD ---
function fetch_updated_record($conn, $record_id, $product_code) {
    $sql_fetch_record = "SELECT * FROM daily_process WHERE id = ? AND product_code = ?";
    $stmt_fetch = $conn->prepare($sql_fetch_record);
    $record_to_edit = null;
    if ($stmt_fetch) {
        $stmt_fetch->bind_param("is", $record_id, $product_code);
        $stmt_fetch->execute();
        $result_fetch = $stmt_fetch->get_result();
        if ($result_fetch->num_rows > 0) {
            $record_to_edit = $result_fetch->fetch_assoc();
        }
        $stmt_fetch->close();
    }
    return $record_to_edit;
}
// --- END OF NEW FUNCTION ---

// Fetch the single record to be edited for the initial page load
$record_to_edit = fetch_updated_record($conn, $record_id, $product_code);

if (!$record_to_edit) {
    $message = "Error: Record not found.";
    $is_success = false;
}

// Fetch processes for the dropdown menu
$processes = [];
$sql_processes = "SELECT process_code, process_name, rate FROM processes ORDER BY process_code ASC";
$result_processes = $conn->query($sql_processes);
if ($result_processes->num_rows > 0) {
    while ($row = $result_processes->fetch_assoc()) {
        $processes[] = [
            'process_code' => $row['process_code'],
            'process_name' => $row['process_name'],
            'rate' => $row['rate']
        ];
    }
}

// Handle form submission
if ($user_rights === 'Admin' && $_SERVER["REQUEST_METHOD"] == "POST") {
    $form_record_id = isset($_POST['id']) ? $conn->real_escape_string($_POST['id']) : '';
    $form_product_code = isset($_POST['product_code']) ? $conn->real_escape_string($_POST['product_code']) : '';

    if (isset($_POST['update'])) {
        // Handle update request
        $date = isset($_POST['date']) ? $conn->real_escape_string($_POST['date']) : '';
        $process_code = isset($_POST['process_code']) ? $conn->real_escape_string($_POST['process_code']) : '';
        $description = isset($_POST['description']) ? $conn->real_escape_string($_POST['description']) : '';
        $quantity = isset($_POST['quantity']) ? (float)$_POST['quantity'] : 0;
        $rate = isset($_POST['rate']) ? (float)$_POST['rate'] : 0;
        $amount = $quantity * $rate;

        // Server-side validation
        if ($quantity <= 0) {
            $message = "Error: Quantity must be a positive number.";
            $is_success = false;
        } else {
            $sql_update = "UPDATE daily_process SET date = ?, process_code = ?, description = ?, quantity = ?, rate = ?, amount = ? WHERE id = ?";
            $stmt_update = $conn->prepare($sql_update);
            if ($stmt_update) {
                $stmt_update->bind_param("sssdddi", $date, $process_code, $description, $quantity, $rate, $amount, $form_record_id);
                if ($stmt_update->execute()) {
                    $message = "Record updated successfully!";
                    $is_success = true;
                    // RE-FETCH the record to show the new values immediately
                    $record_to_edit = fetch_updated_record($conn, $form_record_id, $form_product_code);
                } else {
                    $message = "Error updating record: " . $stmt_update->error;
                    $is_success = false;
                }
                $stmt_update->close();
            } else {
                $message = "Error preparing update statement: " . $conn->error;
                $is_success = false;
            }
        }
    } elseif (isset($_POST['delete'])) {
        // Handle delete request
        $sql_delete = "DELETE FROM daily_process WHERE id = ?";
        $stmt_delete = $conn->prepare($sql_delete);
        if ($stmt_delete) {
            $stmt_delete->bind_param("i", $form_record_id);
            if ($stmt_delete->execute()) {
                header("Location: daily_process.php?product_code=" . urlencode($form_product_code) . "&status=deleted");
                exit();
            } else {
                $message = "Error deleting record: " . $stmt_delete->error;
                $is_success = false;
            }
            $stmt_delete->close();
        } else {
            $message = "Error preparing delete statement: " . $conn->error;
            $is_success = false;
        }
    }
} elseif ($user_rights !== 'Admin' && $_SERVER["REQUEST_METHOD"] == "POST") {
    // Display an error message if a non-admin user attempts a POST request
    $message = "You do not have permission to edit or delete this record.";
    $is_success = false;
}

// Get product information for the header
$product_description = "Product description not found.";
$product_image = "https://placehold.co/100x100/A2D2FF/070A34?text=No+Image";
if (!empty($product_code)) {
    $sql_product = "SELECT item_description, product_image FROM products WHERE product_code = ?";
    $stmt_product = $conn->prepare($sql_product);
    if ($stmt_product) {
        $stmt_product->bind_param("s", $product_code);
        $stmt_product->execute();
        $result_product = $stmt_product->get_result();
        if ($result_product->num_rows > 0) {
            $row_product = $result_product->fetch_assoc();
            $product_description = htmlspecialchars($row_product['item_description']);
            if (!empty($row_product['product_image'])) {
                $product_image = "uploads/" . htmlspecialchars($row_product['product_image']);
            }
        }
        $stmt_product->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 Daily Process</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;
        }

        .info-header {
            display: flex;
            align-items: center;
            gap: 20px;
            margin-bottom: 20px;
            padding: 15px;
            background-color: #eaf6ff;
            border-radius: 8px;
            border: 1px solid #b3d9ff;
        }
        
        .info-header img {
            width: 100px;
            height: 100px;
            border-radius: 8px;
            object-fit: cover;
            border: 2px solid #3498db;
        }

        .info-header .product-details {
            display: flex;
            flex-direction: column;
        }

        .info-header p {
            margin: 0;
            font-weight: 500;
        }

        .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-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #555;
        }

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

        input[type="text"]:focus, input[type="date"]:focus, input[type="number"]:focus, textarea:focus, select:focus {
            border-color: #3498db;
            box-shadow: 0 0 8px rgba(52, 152, 219, 0.2);
            outline: none;
        }

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

        .button-group {
            display: flex;
            gap: 15px;
            margin-top: 20px;
        }
        
        button {
            flex: 1;
            padding: 15px;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 18px;
            font-weight: bold;
            cursor: pointer;
            transition: background-color 0.3s, transform 0.2s;
        }

        .update-button {
            background-color: #3498db;
        }

        .delete-button {
            background-color: #e74c3c;
        }
        
        /* ADDED: Style for disabled buttons/inputs */
        button:disabled {
            background-color: #bdc3c7;
            cursor: not-allowed;
            transform: none;
        }
        
        .form-control:disabled {
            background-color: #ecf0f1;
            cursor: not-allowed;
        }

        button:hover:not(:disabled) {
            transform: translateY(-2px);
        }
        
        .update-button:hover:not(:disabled) {
            background-color: #2980b9;
        }

        .delete-button:hover:not(:disabled) {
            background-color: #c0392b;
        }

        .back-link {
            display: inline-block;
            margin-top: 20px;
            color: #3498db;
            text-decoration: none;
            font-weight: bold;
            transition: color 0.3s;
        }

        .back-link:hover {
            color: #2980b9;
            text-decoration: underline;
        }
        
        .readonly-field {
            background-color: #ecf0f1;
            color: #7f8c8d;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>Edit Daily Process Record</h2>

        <?php if ($message): ?>
            <div class="alert-message <?php echo $is_success ? 'alert-success' : 'alert-error'; ?>">
                <p><?php echo htmlspecialchars($message); ?></p>
            </div>
        <?php endif; ?>

        <?php if ($record_to_edit): ?>
            <div class="info-header">
                <img src="<?php echo htmlspecialchars($product_image); ?>" alt="Product Image" onerror="this.src='https://placehold.co/100x100/A2D2FF/070A34?text=No+Image';">
                <div class="product-details">
                    <p><strong>Product Code:</strong> <?php echo htmlspecialchars($product_code); ?></p>
                    <p><strong>Description:</strong> <?php echo $product_description; ?></p>
                </div>
            </div>

            <form action="" method="post">
                <input type="hidden" name="id" value="<?php echo htmlspecialchars($record_to_edit['id']); ?>">
                <input type="hidden" name="product_code" value="<?php echo htmlspecialchars($product_code); ?>">
                
                <div class="form-group">
                    <label for="date">Date</label>
                    <input type="date" id="date" name="date" value="<?php echo htmlspecialchars($record_to_edit['date']); ?>" required <?php echo ($user_rights !== 'Admin') ? 'disabled' : ''; ?>>
                </div>

                <div class="form-group">
                    <label for="process_code">Process</label>
                    <select id="process_code" name="process_code" required onchange="updateRateFromProcesses()" <?php echo ($user_rights !== 'Admin') ? 'disabled' : ''; ?>>
                        <option value="" disabled>Select a process</option>
                        <?php foreach ($processes as $process): ?>
                            <option value="<?php echo htmlspecialchars($process['process_code']); ?>" data-rate="<?php echo htmlspecialchars($process['rate']); ?>" <?php echo $record_to_edit['process_code'] == $process['process_code'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($process['process_name']); ?> (<?php echo htmlspecialchars($process['process_code']); ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="form-group">
                    <label for="description">Description</label>
                    <textarea id="description" name="description" <?php echo ($user_rights !== 'Admin') ? 'disabled' : ''; ?>><?php echo htmlspecialchars($record_to_edit['description']); ?></textarea>
                </div>

                <div class="form-group">
                    <label for="quantity">Quantity</label>
                    <input type="number" id="quantity" name="quantity" min="0.01" step="0.01" value="<?php echo htmlspecialchars($record_to_edit['quantity']); ?>" required oninput="updateAmount()" <?php echo ($user_rights !== 'Admin') ? 'disabled' : ''; ?>>
                </div>
                
                <div class="form-group">
                    <label for="rate">Rate</label>
                    <input type="number" id="rate" name="rate" value="<?php echo htmlspecialchars($record_to_edit['rate']); ?>" <?php echo ($user_rights !== 'Admin') ? 'readonly class="readonly-field"' : ''; ?> oninput="updateAmount()">
                </div>

                <div class="form-group">
                    <label for="amount">Amount</label>
                    <input type="number" id="amount" name="amount" value="<?php echo htmlspecialchars($record_to_edit['amount']); ?>" readonly class="readonly-field">
                </div>

                <div class="button-group">
                    <button type="submit" name="update" class="update-button" <?php echo ($user_rights !== 'Admin') ? 'disabled' : ''; ?>>Update Record</button>
                    <button type="submit" name="delete" class="delete-button" <?php echo ($user_rights !== 'Admin') ? 'disabled' : ''; ?>>Delete Record</button>
                </div>
            </form>
        <?php else: ?>
            <p style="text-align: center;">Record not found or invalid access.</p>
        <?php endif; ?>

        <a href="daily_process.php?product_code=<?php echo urlencode($product_code); ?>" class="back-link">&larr; Back to Daily Process</a>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var quantityInput = document.getElementById('quantity');
            var processSelect = document.getElementById('process_code');
            var rateInput = document.getElementById('rate');

            if (quantityInput && !quantityInput.disabled) {
                quantityInput.addEventListener('input', updateAmount);
            }
            if (processSelect && !processSelect.disabled) {
                // Add event listener for process change
                processSelect.addEventListener('change', function() {
                    updateRateFromProcesses();
                });
            }
            if (rateInput && !rateInput.disabled) {
                rateInput.addEventListener('input', updateAmount);
            }

            // Initial calculation on page load
            updateAmount();
        });

        function updateRateFromProcesses() {
            var select = document.getElementById('process_code');
            var selectedOption = select.options[select.selectedIndex];
            var rate = selectedOption.getAttribute('data-rate');
            document.getElementById('rate').value = rate;
            updateAmount();
        }

        function updateAmount() {
            var quantity = parseFloat(document.getElementById('quantity').value) || 0;
            var rate = parseFloat(document.getElementById('rate').value) || 0;
            var amount = (quantity * rate).toFixed(2);
            document.getElementById('amount').value = amount;
        }
    </script>
</body>
</html>