<?php
session_start();
include 'db.php';

/*
|--------------------------------------------------------------------------
| RESTAURANT SHIFT CLOSE (FINAL VERSION)
|--------------------------------------------------------------------------
| - Calculates sales totals
| - Splits restaurant vs POS
| - Splits cash vs bank
| - Saves shift record
| - Marks orders as reconciled
| - Redirects to restaurant_shift.php
|--------------------------------------------------------------------------
*/

$current_user = $_SESSION['username'] ?? 'SYSTEM';

$date_from = $_GET['date_from'] ?? date('Y-m-d');
$date_to   = $_GET['date_to'] ?? date('Y-m-d');

/* ================= CHECK IF SHIFT ALREADY CLOSED ================= */

$check = $conn->query("
    SELECT id
    FROM restaurant_shifts
    WHERE DATE(date_from) = '$date_from'
      AND status = 'CLOSED'
    LIMIT 1
");

if ($check && $check->num_rows > 0) {

    $_SESSION['error'] = "Shift already closed for {$date_from}.";
    header("Location: restaurant_shift.php");
    exit;
}

/* ================= GET SALES DATA ================= */

$result = $conn->query("
    SELECT
        s.total,
        s.payment_method,
        r.id AS restaurant_order_id
    FROM sales s
    LEFT JOIN restaurant_orders r
        ON r.id = s.order_id
    WHERE DATE(s.sales_date)
          BETWEEN '$date_from' AND '$date_to'
");

/* ================= CALCULATE TOTALS ================= */

$total_sales      = 0;
$cash_sales       = 0;
$bank_sales       = 0;
$restaurant_sales = 0;
$pos_sales        = 0;

while ($row = $result->fetch_assoc()) {

    $amount = (float)$row['total'];

    $total_sales += $amount;

    // CASH / BANK SPLIT
    $method = strtolower(trim($row['payment_method']));

    if ($method === 'cash') {
        $cash_sales += $amount;
    } else {
        $bank_sales += $amount;
    }

    // RESTAURANT / POS SPLIT
    if (!empty($row['restaurant_order_id'])) {
        $restaurant_sales += $amount;
    } else {
        $pos_sales += $amount;
    }
}

/* ================= SHIFT NUMBER ================= */

$shift_no = 'RAMS-' . date('YmdHis');

/* ================= INSERT SHIFT ================= */

$stmt = $conn->prepare("
    INSERT INTO restaurant_shifts
    (
        shift_no,
        date_from,
        date_to,
        total_sales,
        cash_sales,
        bank_sales,
        restaurant_sales,
        pos_sales,
        closed_by,
        status
    )
    VALUES
    (?, ?, ?, ?, ?, ?, ?, ?, ?, 'CLOSED')
");

$stmt->bind_param(
    "sssddddds",
    $shift_no,
    $date_from,
    $date_to,
    $total_sales,
    $cash_sales,
    $bank_sales,
    $restaurant_sales,
    $pos_sales,
    $current_user
);

if (!$stmt->execute()) {

    $_SESSION['error'] = "Error closing shift: " . $stmt->error;

    header("Location: restaurant_shift.php");
    exit;
}

/* ================= MARK ORDERS AS RECONCILED ================= */

$conn->query("
    UPDATE restaurant_orders
    SET is_reconciled = 1
    WHERE DATE(created_at)
          BETWEEN '$date_from' AND '$date_to'
");

/* ================= SUCCESS MESSAGE ================= */

$_SESSION['success'] =
    "Shift Closed Successfully. Shift No: {$shift_no} | Total: MK "
    . number_format($total_sales, 2);

header("Location: restaurant_shift.php");
exit;
?>