<?php
require_once './shikanisha.kts.php';

session_start();
if (!isset($_SESSION['employee_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not authorized']);
    exit();
}

$employee_id = $_SESSION['employee_id'];
$ending_cash = isset($_POST['ending_cash']) ? floatval($_POST['ending_cash']) : 0;

// Get active shift
$stmt = $conn->prepare("SELECT * FROM shifts WHERE employee_id = ? AND status = 'active'");
$stmt->bind_param("i", $employee_id);
$stmt->execute();
$shift = $stmt->get_result()->fetch_assoc();

if (!$shift) {
    echo json_encode(['success' => false, 'message' => 'No active shift found']);
    exit();
}

// Calculate totals for the shift
$transactions_query = "
    SELECT p.payment_method, SUM(p.amount) as total_amount, COUNT(*) as transaction_count
    FROM payments p
    JOIN transaction_receipts tr ON p.trans_id = tr.trans_id
    WHERE tr.seller_date >= ? AND tr.seller_date <= NOW() AND tr.seller_id = ?
    GROUP BY p.payment_method
";

$stmt = $conn->prepare($transactions_query);
$stmt->bind_param("si", $shift['start_time'], $employee_id);
$stmt->execute();
$payment_methods = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Insert shift summaries
$insert_summary = $conn->prepare("INSERT INTO shift_summaries (shift_id, payment_method, total_amount, transaction_count) VALUES (?, ?, ?, ?)");

foreach ($payment_methods as $method) {
    $insert_summary->bind_param("isdi", $shift['shift_id'], $method['payment_method'], $method['total_amount'], $method['transaction_count']);
    $insert_summary->execute();
}

// Update shift to closed
$update_shift = $conn->prepare("UPDATE shifts SET end_time = NOW(), ending_cash = ?, status = 'closed' WHERE shift_id = ?");
$update_shift->bind_param("di", $ending_cash, $shift['shift_id']);

if ($update_shift->execute()) {
    echo json_encode([
        'success' => true, 
        'message' => 'Shift ended successfully',
        'shift_id' => $shift['shift_id']
    ]);
} else {
    echo json_encode(['success' => false, 'message' => 'Error ending shift']);
}

$stmt->close();
$insert_summary->close();
$update_shift->close();
$conn->close();
?>