<?php
// Start the session to access the user's session ID
session_start();

// Redirect to login page if user_id is not set in the session
if (!isset($_SESSION['user_id'])) {
    // It's good practice to set the status code for redirects
    http_response_code(302);
    header('Location: login.php');
    exit(); // Stop further script execution
}

// --- PHP Backend Logic ---
// This script handles the daily process data entry, including validation and saving to the database.

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

// Initialize variables
$product_code = "";
$product_description = "Product description not found.";
$product_image = "https://placehold.co/100x100/A2D2FF/070A34?text=No+Image"; // Placeholder image
$message = "";
$is_success = false;
$user_id = $_SESSION['user_id']; // Get the user ID from the session

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

// Retrieve product information from URL parameter and database
if (isset($_GET['product_code'])) {
    $product_code = $conn->real_escape_string($_GET['product_code']);
    
    // Use prepared statement to fetch product details
    $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();
    }
}

// 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 ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
    // Sanitize and validate user inputs
    $form_product_code = isset($_POST['product_code']) ? $conn->real_escape_string($_POST['product_code']) : '';
    $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;
    
    // Calculate the amount
    $amount = $quantity * $rate;

    // Server-side validation
    if ($quantity <= 0) {
        $message = "Error: Quantity must be a positive number.";
        $is_success = false;
    } else {
        // SQL query to insert data, including the new 'user_id' field
        $sql_insert = "INSERT INTO daily_process (product_code, date, process_code, description, quantity, rate, amount, user_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        
        // Use a prepared statement to prevent SQL injection
        $stmt_insert = $conn->prepare($sql_insert);
        if ($stmt_insert) {
            // Bind parameters, including the new user_id parameter
            $stmt_insert->bind_param("ssssddds", $form_product_code, $date, $process_code, $description, $quantity, $rate, $amount, $user_id);

            if ($stmt_insert->execute()) {
                // Use a redirect to prevent form resubmission on refresh (Post/Redirect/Get pattern)
                header("Location: daily_process.php?product_code=" . urlencode($form_product_code) . "&status=success");
                exit();
            } else {
                $message = "Error saving record: " . $stmt_insert->error;
                $is_success = false;
            }
            $stmt_insert->close();
        } else {
            $message = "Error preparing statement: " . $conn->error;
            $is_success = false;
        }
    }
}

// Display success message from the URL parameter
if (isset($_GET['status']) && $_GET['status'] == 'success') {
    $message = "Record saved successfully!";
    $is_success = true;
}

// Fetch daily process history for the selected product, joining with processes table for the name
$daily_process_history = [];
$total_amount = 0;

if (!empty($product_code)) {
    // Modified SQL query to select the user_id as well
    $sql_history = "SELECT dp.id, dp.date, dp.process_code, p.process_name, dp.description, dp.quantity, dp.rate, dp.amount, dp.user_id
                    FROM daily_process AS dp
                    JOIN processes AS p ON dp.process_code = p.process_code
                    WHERE dp.product_code = ? 
                    ORDER BY dp.date DESC, dp.created_at DESC";
    $stmt_history = $conn->prepare($sql_history);
    if ($stmt_history) {
        $stmt_history->bind_param("s", $product_code);
        $stmt_history->execute();
        $result_history = $stmt_history->get_result();

        if ($result_history->num_rows > 0) {
            while ($row = $result_history->fetch_assoc()) {
                $daily_process_history[] = $row;
                // Calculate total amount while fetching
                $total_amount += $row['amount'];
            }
        }
        $stmt_history->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>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%; /* Adjusted width */
            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 {
            display: block;
            width: 50%; /* Adjusted width */
            padding: 15px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 18px;
            font-weight: bold;
            cursor: pointer;
            transition: background-color 0.3s, transform 0.2s;
            margin-top: 20px;
        }

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

        .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;
        }
        
        .calculated-value {
            font-weight: bold;
            font-size: 1.2em;
            color: #2c3e50;
            padding: 12px;
            background-color: #ecf0f1;
            border-radius: 8px;
            border: 1px solid #bdc3c7;
            display: inline-block;
            width: 50%;
            box-sizing: border-box;
        }
        
        .readonly-field {
            background-color: #ecf0f1;
            color: #7f8c8d;
        }

        .history-section {
            margin-top: 50px;
        }
        
        .history-section h3 {
            text-align: center;
            color: #34495e;
            margin-bottom: 20px;
            font-weight: 700;
        }

        .history-table-container {
            overflow-x: auto;
        }

        .history-table {
            width: 100%;
            border-collapse: collapse;
        }

        .history-table th, .history-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        .history-table th {
            background-color: #34495e;
            color: white;
        }

        .history-table tr:nth-child(even) {
            background-color: #f2f2f2;
        }

        .history-table tfoot td {
            font-weight: bold;
            background-color: #d1e7f9;
        }

        .history-table tbody a {
            color: #3498db;
            text-decoration: none;
        }

        .history-table tbody a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>Daily Process for Product</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; ?>

        <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="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 date('Y-m-d'); ?>" required>
            </div>

            <div class="form-group">
                <label for="process_code">Process</label>
                <select id="process_code" name="process_code" required onchange="updateRate()">
                    <option value="" selected 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 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"></textarea>
            </div>

            <div class="form-group">
                <label for="quantity">Quantity</label>
                <input type="number" id="quantity" name="quantity" min="0.01" step="0.01" required oninput="updateAmount()">
            </div>
                <label for="rate">Rate</label>
                <input type="number" id="rate" name="rate" required oninput="updateAmount()">
            </div>

            <div class="form-group">
                <label for="amount">Amount</label>
                <input type="number" id="amount" name="amount" readonly class="readonly-field">
            </div>

            <button type="submit" name="submit">Save Daily Process</button>
        </form>

        <div class="history-section">
            <h3>Daily Process History</h3>
            <?php if (empty($daily_process_history)): ?>
                <p style="text-align: center;">No history found for this product.</p>
            <?php else: ?>
                <div class="history-table-container">
                    <table class="history-table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Process Name</th>
                                <th>Description</th>
                                <th>Quantity</th>
                                <th>Rate</th>
                                <th>Amount</th>
                                <th>User ID</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($daily_process_history as $record): ?>
                            <tr>
                                <td><a href="edit_daily_process.php?product_code=<?php echo urlencode($product_code); ?>&id=<?php echo urlencode($record['id']); ?>"><?php echo date('d/m/Y', strtotime($record['date'])); ?></a></td>
                                <td><?php echo htmlspecialchars($record['process_name']); ?></td>
                                <td><?php echo htmlspecialchars($record['description']); ?></td>
                                <td><?php echo htmlspecialchars($record['quantity']); ?></td>
                                <td><?php echo htmlspecialchars($record['rate']); ?></td>
                                <td><?php echo htmlspecialchars($record['amount']); ?></td>
                                <td><?php echo htmlspecialchars($record['user_id']); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="4"><strong>Total</strong></td>
                                <td></td>
                                <td><strong><?php echo number_format($total_amount, 2); ?></strong></td>
                                <td></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

<script>
    // This function populates the rate field when a process is selected.
    // It will still run, but the user can now override the value manually.
    function updateRate() {
        var select = document.getElementById('process_code');
        var selectedOption = select.options[select.selectedIndex];
        var rate = selectedOption.getAttribute('data-rate');
        document.getElementById('rate').value = rate;
        updateAmount();
    }

    // This function now calculates the amount whenever the quantity or rate is changed.
    function updateAmount() {
        var quantity = parseFloat(document.getElementById('quantity').value) || 0;
        var rate = parseFloat(document.getElementById('rate').value) || 0; // The rate value is read from the input
        var amount = (quantity * rate).toFixed(2);
        document.getElementById('amount').value = amount;
    }
</script>
</body>
</html>
