<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('../config/config.php');
session_start();

$order_date = date('Y-m-d'); // current date
$branch_id = isset($_SESSION['branch_id']) ? $_SESSION['branch_id'] : 0;

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

    switch ($action) {
        case 'add':
            if (!isset($_POST['customer_id'], $_POST['site_name'], $_POST['order_quantity_m3'], $_POST['marketing_person_id'], $_POST['execution_date'])) {
                echo "Error: Required fields are missing.";
                exit();
            }

            $order_no = "ORD" . date("YmdHis");

            $stmt = $conn->prepare("INSERT INTO orders (order_date,
                marketing_person_id, order_no, customer_id, execution_date, site_name,
                aggregate_12m_kg, aggregate_sand_kg, aggregate_20mm_1_kg, aggregate_20mm_2_kg,
                cement_cem1_kg, cement_cem2_kg, admixture_admix1_kg, admixture_admix2_kg,
                water_kg, order_quantity_m3, branch_id, status
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,'active')");

            $stmt->bind_param("sisissddddddddddi",$order_date,
                $_POST['marketing_person_id'], $order_no, $_POST['customer_id'], $_POST['execution_date'], $_POST['site_name'],
                $_POST['aggregate_12m_kg'], $_POST['aggregate_sand_kg'], $_POST['aggregate_20mm_1_kg'], $_POST['aggregate_20mm_2_kg'],
                $_POST['cement_cem1_kg'], $_POST['cement_cem2_kg'], $_POST['admixture_admix1_kg'], $_POST['admixture_admix2_kg'],
                $_POST['water_kg'], $_POST['order_quantity_m3'], $branch_id
            );

            if ($stmt->execute()) {
                echo "Order added successfully!";
            } else {
                echo "Error: " . $stmt->error;
            }

            $stmt->close();
            break;

       
           case 'edit':
                if (!isset($_POST['id'], $_POST['customer_id'], $_POST['site_name'], $_POST['order_quantity_m3'], $_POST['marketing_person_id'], $_POST['execution_date'])) {
                    echo "Error: Required fields are missing.";
                    exit();
                }
            
                $stmt = $conn->prepare("UPDATE orders SET
                    marketing_person_id=?, customer_id=?, execution_date=?, site_name=?,
                    aggregate_12m_kg=?, aggregate_sand_kg=?, aggregate_20mm_1_kg=?, aggregate_20mm_2_kg=?,
                    cement_cem1_kg=?, cement_cem2_kg=?, admixture_admix1_kg=?, admixture_admix2_kg=?,
                    water_kg=?, order_quantity_m3=?
                    WHERE id=? AND branch_id=?");
            
                $stmt->bind_param("iissddddddddddii",
                    $_POST['marketing_person_id'],
                    $_POST['customer_id'],
                    $_POST['execution_date'],
                    $_POST['site_name'],
                    $_POST['aggregate_12m_kg'],
                    $_POST['aggregate_sand_kg'],
                    $_POST['aggregate_20mm_1_kg'],
                    $_POST['aggregate_20mm_2_kg'],
                    $_POST['cement_cem1_kg'],
                    $_POST['cement_cem2_kg'],
                    $_POST['admixture_admix1_kg'],
                    $_POST['admixture_admix2_kg'],
                    $_POST['water_kg'],
                    $_POST['order_quantity_m3'],
                    $_POST['id'],
                    $branch_id
                );
            
                if ($stmt->execute()) {
                    echo "Order updated successfully!";
                } else {
                    echo "Error: " . $stmt->error;
                }
            
                $stmt->close();
                break;


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

            $stmt = $conn->prepare("UPDATE orders SET status='inactive' WHERE id=? AND branch_id=?");
            $stmt->bind_param("ii", $id, $branch_id);

            if ($stmt->execute()) {
                echo "Order deleted successfully!";
            } else {
                echo "Error: " . $stmt->error;
            }

            $stmt->close();
            break;

        default:
            echo "Invalid action!";
            break;
    }

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

if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['id']) && isset($_GET['action']) && $_GET['action'] == 'view') {
    $id = $_GET['id'];

    $stmt = $conn->prepare("SELECT  DATE_FORMAT(o.created_at, '%d-%m-%Y') as order_date,
        o.id, o.order_no, o.customer_id, o.site_name, DATE_FORMAT(o.execution_date, '%d-%m-%Y') as execution_date,
        o.aggregate_12m_kg, o.aggregate_sand_kg, o.aggregate_20mm_1_kg, o.aggregate_20mm_2_kg,
        o.cement_cem1_kg, o.cement_cem2_kg, o.admixture_admix1_kg, o.admixture_admix2_kg,
        o.water_kg, o.order_quantity_m3, o.marketing_person_id,
        c.customer_name, m.name as marketing_name
        FROM orders o
        JOIN customers c ON o.customer_id = c.id
        LEFT JOIN marketing_persons m ON o.marketing_person_id = m.id
        WHERE o.id = ? AND o.branch_id = ?");

    $stmt->bind_param("ii", $id, $branch_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result && $data = $result->fetch_assoc()) {
        echo json_encode($data);
    } else {
        echo json_encode(array("error" => "No data found"));
    }

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