<?php
/* ============================================================================
   REPLICA WOOD — PLANNING AJAX ACTION ROUTER
   ========================================================================= */
session_start();
include("../../../include/startup.php");

if (function_exists('mysqli_report')) {
    mysqli_report(MYSQLI_REPORT_OFF);
}
set_exception_handler(function ($e) {
    while (ob_get_level()) { ob_end_clean(); }
    header('Content-Type: application/json');
    echo json_encode(["status" => "failure", "message" => "Server error: " . $e->getMessage()]);
    exit;
});

if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'save_requirement') {

    $part_id = intval($_REQUEST['part_id']);
    $req_date = mysqli_real_escape_string($conn, $_REQUEST['req_date']);
    $req_qty = intval($_REQUEST['req_qty']);
    $user_id = intval($_SESSION['admin_id'] ?? 0);
    $now = date('Y-m-d H:i:s');

    if ($part_id <= 0 || !$req_date || $req_qty < 0) {
        echo json_encode(["status" => "failure", "message" => "Invalid input"]);
        die;
    }

    $check = mysqli_query($conn, "SELECT id FROM item_management 
                                   WHERE id = $part_id 
                                   AND replica_wood = 1 
                                   LIMIT 1");
    if (!$check || mysqli_num_rows($check) == 0) {
        echo json_encode(["status" => "failure", "message" => "Item is not a Replica Wood item"]);
        die;
    }

    // Upsert — table now only ever stores req_qty, nothing derived. Works
    // for any date, today or future.
    $sql = "INSERT INTO replica_wood_planning 
                (part_id, req_date, req_qty, created_by, created_on, updated_by, updated_on)
            VALUES 
                ($part_id, '$req_date', $req_qty, $user_id, '$now', $user_id, '$now')
            ON DUPLICATE KEY UPDATE 
                req_qty = $req_qty,
                updated_by = $user_id,
                updated_on = '$now'";

    if (mysqli_query($conn, $sql)) {
        echo json_encode(["status" => "success", "message" => "Requirement saved successfully"]);
    } else {
        echo json_encode(["status" => "failure", "message" => mysqli_error($conn)]);
    }
    die;

} elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == 'save_bespoke_color') {

    $req_date   = mysqli_real_escape_string($conn, $_REQUEST['req_date'] ?? '');
    $color_text = trim($_REQUEST['color_text'] ?? '');
    $user_id    = intval($_SESSION['admin_id'] ?? 0);
    $now        = date('Y-m-d H:i:s');

    if (!$req_date || $color_text === '') {
        echo json_encode(["status" => "failure", "message" => "Please enter a colour name"]);
        die;
    }
    if (mb_strlen($color_text) > 100) {
        echo json_encode(["status" => "failure", "message" => "Colour name is too long (max 100 characters)"]);
        die;
    }
    $color_text_esc = mysqli_real_escape_string($conn, $color_text);

    $sql = "INSERT INTO replica_wood_bespoke_color
                (req_date, color_text, created_by, created_on, updated_by, updated_on)
            VALUES
                ('$req_date', '$color_text_esc', $user_id, '$now', $user_id, '$now')
            ON DUPLICATE KEY UPDATE
                color_text = '$color_text_esc',
                updated_by = $user_id,
                updated_on = '$now'";

    if (mysqli_query($conn, $sql)) {
        echo json_encode(["status" => "success", "message" => "Bespoke colour saved for $req_date"]);
    } else {
        echo json_encode(["status" => "failure", "message" => mysqli_error($conn)]);
    }
    die;

} elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == 'clear_arrears') {

    // No status column any more — "clearing" arrears for ONE item now means
    // writing req_qty DOWN to whatever was actually produced (from
    // replica_wood_count_log) for every past-dated row, which makes the
    // GREATEST(req_qty - produced, 0) sum in rw_get_arrears() zero for
    // those rows going forward. This overwrites the original requirement
    // value rather than tracking a separate "cleared" flag — a deliberate
    // simplification: once cleared, the original ask isn't recoverable,
    // only "what was actually produced" remains.
    $part_id     = intval($_REQUEST['part_id']);
    $before_date = mysqli_real_escape_string($conn, $_REQUEST['req_date'] ?? date('Y-m-d'));
    $user_id     = intval($_SESSION['admin_id'] ?? 0);
    $now         = date('Y-m-d H:i:s');

    $sql = "UPDATE replica_wood_planning p
            LEFT JOIN replica_wood_count_log c
                ON c.part_id = p.part_id AND c.req_date = p.req_date
            SET p.req_qty = COALESCE(c.quantity, 0),
                p.updated_by = $user_id,
                p.updated_on = '$now'
            WHERE p.part_id = $part_id
              AND p.req_date < '$before_date'
              AND p.req_qty > COALESCE(c.quantity, 0)";

    if (mysqli_query($conn, $sql)) {
        echo json_encode(["status" => "success", "message" => "Arrears cleared for this item"]);
    } else {
        echo json_encode(["status" => "failure", "message" => mysqli_error($conn)]);
    }
    die;

} elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == 'clear_all_arrears') {

    // Same idea, no part_id filter — clears every item's backlog before
    // the viewed date in one pass.
    $before_date = mysqli_real_escape_string($conn, $_REQUEST['req_date'] ?? date('Y-m-d'));
    $user_id     = intval($_SESSION['admin_id'] ?? 0);
    $now         = date('Y-m-d H:i:s');

    $sql = "UPDATE replica_wood_planning p
            LEFT JOIN replica_wood_count_log c
                ON c.part_id = p.part_id AND c.req_date = p.req_date
            SET p.req_qty = COALESCE(c.quantity, 0),
                p.updated_by = $user_id,
                p.updated_on = '$now'
            WHERE p.req_date < '$before_date'
              AND p.req_qty > COALESCE(c.quantity, 0)";

    if (mysqli_query($conn, $sql)) {
        echo json_encode(["status" => "success", "message" => "All arrears cleared"]);
    } else {
        echo json_encode(["status" => "failure", "message" => mysqli_error($conn)]);
    }
    die;

} else {
    echo json_encode(["status" => "failure", "message" => "Unknown action"]);
    die;
}
?>