<?php
include('../config/config.php');
include('../config/session_check.php'); 
$branch_id = $_SESSION['branch_id']; // Ensure DB connection is established

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $action = isset($_POST['action']) ? $_POST['action'] : '';
    $id = isset($_POST['id']) ? $_POST['id'] : '';

    switch ($action) {
                case 'add':
                    if (!isset($_POST['order_id']) || !isset($_POST['batch_date']) || !isset($_POST['batch_start_time']) || !isset($_POST['batch_end_time']) || 
                        !isset($_POST['batch_number']) || !isset($_POST['process_quantity']) || !isset($_POST['order_qty']) || 
                        !isset($_POST['truck_id']) || !isset($_POST['recipe_id']) || !isset($_POST['driver_id'])) {
                        error_log("Error: Required fields are missing.");
                        echo json_encode(["error" => "Missing Required Fields"]);
                        exit();
                    }
                
                    $order_id = intval($_POST['order_id']);
                    $batch_date = $_POST['batch_date'];
                    $batch_start_time = $_POST['batch_start_time'];
                    $batch_end_time = $_POST['batch_end_time'];
                    $batch_number = $_POST['batch_number'];
                    $process_quantity = floatval($_POST['process_quantity']);
                    $order_quantity = floatval($_POST['order_qty']);
                    $truck_id = intval($_POST['truck_id']);
                    $recipe_id = intval($_POST['recipe_id']);
                    $driver_id = intval($_POST['driver_id']);
                
                    error_log("Order ID: $order_id | Truck: $truck_id | Recipe: $recipe_id | Driver: $driver_id");
                
                    // Insert order processing record
                    $stmt = $conn->prepare("INSERT INTO order_processing (order_id, batch_date, batch_start_time, batch_end_time, batch_number, 
                                            production_quantity, ordered_quantity, truck_id, recipe_id, driver_id,branch_id,status, created_at) 
                                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?, 'active', NOW())");
                
                    if (!$stmt) {
                        error_log("SQL Error: " . $conn->error);
                        echo json_encode(["error" => "SQL Error: " . $conn->error]);
                        exit();
                    }
                
                    $stmt->bind_param("issssdiiiii", $order_id, $batch_date, $batch_start_time, $batch_end_time, $batch_number, 
                                      $process_quantity, $order_quantity, $truck_id, $recipe_id, $driver_id,$branch_id);
                
                    if ($stmt->execute()) {
                        error_log("Order Processing Added Successfully!");
                
                        // Update process_qty in orders table
                        $update_stmt = $conn->prepare("UPDATE orders SET process_qty = process_qty + ? WHERE id = ?");
                        if (!$update_stmt) {
                            error_log("SQL Update Error: " . $conn->error);
                            echo json_encode(["error" => "SQL Update Error: " . $conn->error]);
                            exit();
                        }
                
                        $update_stmt->bind_param("di", $process_quantity, $order_id);
                        if ($update_stmt->execute()) {
                            echo json_encode(["success" => "Order Processing Added Successfully! Production Quantity Updated."]);
                        } else {
                            echo json_encode(["error" => "Failed to update production quantity."]);
                        }
                
                        $update_stmt->close();
                    } else {
                        error_log("Insert Error: " . $stmt->error);
                        echo json_encode(["error" => "Insert Error: " . $stmt->error]);
                    }
                
                    $stmt->close();
                    exit();

            

            
            case 'get_order_details':
                if ($_SERVER["REQUEST_METHOD"] != "POST") {
                    echo json_encode(["error" => "Invalid request method. Use POST."]);
                    exit();
                }
            
                if (!isset($_POST['order_id'])) {
                    echo json_encode(["error" => "Missing Order ID."]);
                    exit();
                }
            
                $order_id = intval($_POST['order_id']);
                
               
            
                // Fetch Order Quantity, Process Quantity, and Remaining Quantity
                $stmt = $conn->prepare("SELECT order_quantity_m3, process_qty, (order_quantity_m3 - process_qty) AS remaining_qty FROM orders WHERE id = ? AND status = 'active'");
                $stmt->bind_param("i", $order_id);
                $stmt->execute();
                $stmt->bind_result($order_quantity_m3, $process_qty, $remaining_qty);
            
                if (!$stmt->fetch()) {
                    echo json_encode(["error" => "Order ID not found"]);
                    exit();
                }
                $stmt->close();
            
                // Fetch the Last Batch Number
                $stmt = $conn->prepare("SELECT IFNULL(MAX(batch_number) + 1, 1) AS next_batch_number FROM order_processing WHERE order_id = ?");
                $stmt->bind_param("i", $order_id);
                $stmt->execute();
                $stmt->bind_result($next_batch_number);
                if (!$stmt->fetch()) {
                    $next_batch_number = 1;
                }
                $stmt->close();
            
                // Return JSON response
                echo json_encode([
                    "order_quantity_m3" => $order_quantity_m3,
                    "remaining_qty" => $remaining_qty,
                    "next_batch_number" => $next_batch_number
                ]);
                exit();
 

           case 'get_order_processing':
    if ($_SERVER["REQUEST_METHOD"] != "POST") {
        echo json_encode(["error" => "Invalid request method. Use POST."]);
        exit();
    }

    if (!isset($_POST['id'])) {
        echo json_encode(["error" => "Missing Order Processing ID."]);
        exit();
    }

    $processing_id = intval($_POST['id']);

    // Log the requested ID
    error_log("Fetching Order Processing Details for ID: " . $processing_id);

    $stmt = $conn->prepare("SELECT op.id, o.order_no, v.reg_no AS truck_no, d.name AS driver_name, 
                                   o.order_quantity_m3 AS ordered_quantity, op.production_quantity AS process_quantity, 
                                   op.batch_date, op.batch_start_time, op.batch_end_time, op.batch_number, 
                                   r.id AS recipe_id, r.recipe_name 
                            FROM order_processing op
                            JOIN orders o ON op.order_id = o.id
                            JOIN vehicles v ON op.truck_id = v.id
                            JOIN drivers d ON op.driver_id = d.id
                            JOIN recipes r ON op.recipe_id = r.id
                            WHERE op.id = ?");
    
    if (!$stmt) {
        error_log("SQL Error: " . $conn->error);
        echo json_encode(["error" => "SQL Error: " . $conn->error]);
        exit();
    }

    $stmt->bind_param("i", $processing_id);
    $stmt->execute();
    $stmt->bind_result($id, $order_no, $truck_no, $driver_name, $ordered_quantity, $process_quantity, 
                       $batch_date, $batch_start_time, $batch_end_time, $batch_number, $recipe_id, $recipe_name);

    if (!$stmt->fetch()) {
        error_log("Order Processing ID " . $processing_id . " not found in database.");
        echo json_encode(["error" => "Order Processing ID not found"]);
        exit();
    }
    $stmt->close();

    error_log("Order Processing Data Found: " . json_encode([
        "id" => $id,
        "order_no" => $order_no,
        "truck_no" => $truck_no,
        "driver_name" => $driver_name,
        "ordered_quantity" => $ordered_quantity,
        "process_quantity" => $process_quantity,
        "batch_date" => $batch_date,
        "batch_start_time" => $batch_start_time,
        "batch_end_time" => $batch_end_time,
        "batch_number" => $batch_number,
        "recipe_id" => $recipe_id,
        "recipe_name" => $recipe_name
    ]));

    echo json_encode([
        "id" => $id,
        "order_no" => $order_no,
        "truck_no" => $truck_no,
        "driver_name" => $driver_name,
        "ordered_quantity" => $ordered_quantity,
        "process_quantity" => $process_quantity,
        "batch_date" => $batch_date,
        "batch_start_time" => $batch_start_time,
        "batch_end_time" => $batch_end_time,
        "batch_number" => $batch_number,
        "recipe_id" => $recipe_id,
        "recipe_name" => $recipe_name
    ]);
    exit();




        case 'edit':
            if (!isset($_POST['id']) || !isset($_POST['process_quantity'])) {
                echo "Error: Required fields are missing.";
                exit();
            }

            $process_quantity = $_POST['process_quantity'];

            $stmt = $conn->prepare("UPDATE order_processing SET production_quantity=? WHERE id=?");
            $stmt->bind_param("di", $process_quantity, $id);
            echo $stmt->execute() ? "Order Processing Updated Successfully!" : "Error: " . $stmt->error;
            $stmt->close();
            break;

        case 'delete':
            if (!isset($_POST['id'])) {
                echo "Error: Missing ID.";
                exit();
            }

            $stmt = $conn->prepare("DELETE FROM order_processing WHERE id=?");
            $stmt->bind_param("i", $id);
            echo $stmt->execute() ? "Order Processing Deleted Successfully!" : "Error: " . $stmt->error;
            $stmt->close();
            break;
            
              default:
                  
        error_log("Invalid action requested: " . $action);
        echo json_encode(["error" => "Invalid action: " . htmlspecialchars($action)]);
        exit();
    }

    $conn->close();
    exit();
}

// Handle GET request for fetching order processing details (Previously in get_order_processing.php)
if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['id'])) {
    $id = $_GET['id'];

    $query = "SELECT 
                op.id, 
                o.order_no, 
                v.reg_no AS truck_no, 
                d.name AS driver_name, 
                op.ordered_quantity, 
                op.production_quantity AS process_quantity,
                op.batch_date, 
                op.batch_start_time, 
                op.batch_end_time, 
                op.batch_number
              FROM order_processing op
              JOIN orders o ON op.order_id = o.id
              JOIN vehicles v ON op.truck_id = v.id
              JOIN drivers d ON op.driver_id = d.id
              WHERE op.id = ?";

    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->bind_result($id, $order_no, $truck_no, $driver_name, $ordered_quantity, $process_quantity, $batch_date, $batch_start_time, $batch_end_time, $batch_number);

    if ($stmt->fetch()) {
        echo json_encode([
            "id" => $id,
            "order_no" => $order_no,
            "truck_no" => $truck_no,
            "driver_name" => $driver_name,
            "ordered_quantity" => $ordered_quantity,
            "process_quantity" => $process_quantity,
            "batch_date" => $batch_date,
            "batch_start_time" => $batch_start_time,
            "batch_end_time" => $batch_end_time,
            "batch_number" => $batch_number
        ]);
    } else {
        echo json_encode(["error" => "No data found"]);
    }

    $stmt->close();
    $conn->close();
    exit();
}
?>
