<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

?>


<?php if(isset($_SESSION['success'])): ?>
<div class="alert alert-success">
    <?= $_SESSION['success']; unset($_SESSION['success']); ?>
</div>
<?php endif; ?>

<?php if(isset($_SESSION['error'])): ?>
<div class="alert alert-danger">
    <?= $_SESSION['error']; unset($_SESSION['error']); ?>
</div>
<?php endif; ?>

<?php



$username      = $_SESSION['username'] ?? 'Guest';
$current_user  = $_SESSION['username'] ?? '';
$current_role  = strtolower($_SESSION['role'] ?? 'guest');

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

/* ================= SHIFT STATUS ================= */
$shift_check = $conn->query("
    SELECT *
    FROM restaurant_shifts
    WHERE DATE(date_from) = '$date_from'
      AND status = 'CLOSED'
    ORDER BY id DESC
    LIMIT 1
");

$shift = $shift_check ? $shift_check->fetch_assoc() : null;
$shift_closed = $shift ? true : false;

/* ================= SALES REPORT ================= */
$sales = $conn->query("
    SELECT
        s.id,
        s.sales_date,
        s.total,
        s.payment_method,
        s.created_by,
        s.order_id,
           s.id,
        r.id AS restaurant_order_id,
        r.table_number,
        r.grand_total,
        r.status

    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'

    ORDER BY s.sales_date ASC
");

/* ================= TOTALS ================= */
$total_cash       = 0;
$total_bank       = 0;
$total_all        = 0;
$total_restaurant = 0;
$total_pos        = 0;

$rows = [];

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

    $rows[] = $row;

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

    $total_all += $amount;

    if (!empty($row['restaurant_order_id'])) {
        $total_restaurant += $amount;
    } else {
        $total_pos += $amount;
    }

    $method = strtolower(trim($row['payment_method']));

    if ($method == 'cash') {
        $total_cash += $amount;
    } else {
        $total_bank += $amount;
    }
}

$potential_cash = $total_cash;
$actual_cash    = $total_cash;
$over_short     = $actual_cash - $potential_cash;

$cashier_name = $rows[0]['created_by'] ?? $current_user;
?>

<style>
body{
    background:#f4f6f9;
    font-family:"Segoe UI",Arial,sans-serif;
}

#printArea{
    background:#fff;
    padding:20px;
    border-radius:10px;
    box-shadow:0 2px 10px rgba(0,0,0,0.08);
}

h2{
    font-weight:700;
    letter-spacing:1px;
}

h4{
    color:#444;
}

table{
    font-size:13px;
}

table th{
    background:#222 !important;
    color:#fff !important;
    font-size:12px;
    text-transform:uppercase;
}

table td{
    padding:6px !important;
}

.btn-dark{
    border-radius:8px;
    padding:8px 15px;
}

.filter-box{
    background:#fff;
    padding:15px;
    border-radius:10px;
    margin-bottom:15px;
    box-shadow:0 1px 6px rgba(0,0,0,0.05);
}

@media print{
    .no-print{
        display:none !important;
    }
}
</style>

<div class="container mt-4">

<!-- ================= CLOSE SHIFT ================= -->
<?php if(!$shift_closed): ?>
<form method="POST" action="restaurant_shift_close.php" class="no-print">
    <button class="btn btn-danger mb-3">
        <i class="fa fa-lock"></i> Close Shift
    </button>
</form>
<?php else: ?>

<button class="btn btn-secondary mb-3 no-print" disabled>
    <i class="fa fa-lock"></i> Shift Already Closed
</button>

<div class="alert alert-warning">
    This shift has already been closed. No further changes are allowed.
</div>

<?php endif; ?>

<!-- ================= FILTER ================= -->
<form method="GET" class="filter-box row no-print">

    <div class="col-md-5">
        <label>From Date</label>
        <input type="date"
               name="date_from"
               value="<?= $date_from ?>"
               class="form-control">
    </div>

    <div class="col-md-5">
        <label>To Date</label>
        <input type="date"
               name="date_to"
               value="<?= $date_to ?>"
               class="form-control">
    </div>

    <div class="col-md-2 d-flex align-items-end">
        <button class="btn btn-success w-100">
            Filter
        </button>
    </div>

</form>

<div id="printArea">

<!-- ================= HEADER ================= -->
<div class="text-center" style="margin-bottom:15px;">

    <img src="assets/logo.png"
         style="width:80px;height:auto;margin-bottom:10px;">

    <h2 style="margin:0;">RAMS EXECUTIVE LODGE</h2>
    <h4 style="margin:5px 0;">Restaurant Cashier Summary Report</h4>

    <p style="margin:0;">
        Phone: +265 993 899 382 / +265 883 899 382
    </p>

</div>

<!-- ================= SHIFT DETAILS ================= -->
<table class="table table-borderless">
<tr>
    <td>
        <b>Shift Date:</b>
        <?= date('d/m/Y', strtotime($date_from)) ?>
        -
        <?= date('d/m/Y', strtotime($date_to)) ?>
    </td>

    <td>
        <b>Time Ended:</b>
        <?= $shift['closed_at'] ?? date('h:i:s A') ?>
    </td>
</tr>

<tr>
    <td>
        <b>Shift No:</b>
       <?= $shift ? $shift['shift_no'] : 'NOT CLOSED' ?>
    </td>

    <td>
        <b>Cashier:</b>
        <?= strtoupper($cashier_name) ?>
    </td>
</tr>
</table>

<!-- ================= SALES DETAILS ================= -->
<table class="table table-bordered">

<thead>
<tr>
    <th>Time Paid</th>
    <th>Date</th>
    <th>Order No</th>
    <th>Status</th>
    <th>Sale Type</th>
    <th>Amount</th>
    <th>Payment Mode</th>
    <th>Cashier</th>
</tr>
</thead>

<tbody>

<?php if(count($rows) > 0): ?>

<?php foreach($rows as $r): ?>

<tr>

    <td>
        <?= date('h:i:s A', strtotime($r['sales_date'])) ?>
    </td>

    <td>
        <?= date('d/m/Y', strtotime($r['sales_date'])) ?>
    </td>

    <td>
       <center> <?= $r['id'] ?: '-' ?></center>
    </td>

    <td>
        <?= $r['status'] ?: '-' ?>
    </td>

    <td>
        <?= !empty($r['restaurant_order_id']) ? 'RESTAURANT' : 'POS' ?>
    </td>

    <td>
        <?= number_format($r['total'],2) ?>
    </td>

    <td>
        <?= strtoupper($r['payment_method']) ?>
    </td>

    <td>
        <?= strtoupper($r['created_by']) ?>
    </td>

</tr>

<?php endforeach; ?>

<?php else: ?>

<tr>
    <td colspan="8">
        No sales found for selected date range.
    </td>
</tr>

<?php endif; ?>

</tbody>

</table>

<!-- ================= SUMMARY ================= -->
<h5>Sales Summary</h5>

<table class="table table-bordered">

<tr>
    <td><b>RESTAURANT SALES</b></td>
    <td><?= number_format($total_restaurant,2) ?></td>
</tr>

<tr>
    <td><b>POS SALES</b></td>
    <td><?= number_format($total_pos,2) ?></td>
</tr>

<tr>
    <td><b>CASH SALES</b></td>
    <td><?= number_format($total_cash,2) ?></td>
</tr>

<tr>
    <td><b>BANK / MOBILE MONEY SALES</b></td>
    <td><?= number_format($total_bank,2) ?></td>
</tr>

<tr>
    <td><b>TOTAL SALES</b></td>
    <td>
        <b><?= number_format($total_all,2) ?></b>
    </td>
</tr>

<tr>
    <td><b>POTENTIAL CASH TURN IN</b></td>
    <td><?= number_format($potential_cash,2) ?></td>
</tr>

<tr>
    <td><b>ACTUAL CASH TURN IN</b></td>
    <td><?= number_format($actual_cash,2) ?></td>
</tr>

<tr>
    <td><b>OVER / SHORT</b></td>
    <td><?= number_format($over_short,2) ?></td>
</tr>

</table>

<!-- ================= SIGNATURES ================= -->
<h5>FOR OFFICIAL USE ONLY</h5>

<table class="table table-bordered">

<tr>

    <td>
        <b>Cashier:</b><br><br>
        <?= strtoupper($cashier_name) ?>
    </td>

    <td>
        Accounts:<br><br><br>
        ______________________
    </td>

    <td>
        Controller:<br><br><br>
        ______________________
    </td>

</tr>

</table>

</div>

<button onclick="printReport()"
        class="btn btn-dark mt-3 no-print">

    <i class="fa fa-print"></i>
    Print Report

</button>

<script>
function printReport(){

    var content =
        document.getElementById('printArea').innerHTML;

    var w = window.open('', '', 'width=1200,height=800');

    w.document.write(`
    <html>
    <head>
    <title>Cashier Summary Report</title>

    <style>

    body{
        font-family:Arial;
        padding:20px;
        font-size:10px;
    }

    table{
        width:100%;
        border-collapse:collapse;
    }

    table,th,td{
        border:1px solid #000;
    }

    th,td{
        padding:4px;
        text-align:center;
        font-size:10px;
    }

    h2,h4,h5{
        text-align:center;
    }

    </style>

    </head>

    <body>
        ${content}
    </body>

    </html>
    `);

    w.document.close();
    w.focus();
    w.print();

}
</script>

<?php include 'includes/footer.php'; ?>