<?php
include "../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();

$today       = date('Y-m-d');
$week_start  = date('Y-m-d', strtotime('monday this week'));
$week_end    = date('Y-m-d', strtotime('sunday this week'));
$month_start = date('Y-m-01');
$month_end   = date('Y-m-t');

function build_rows($db, $date_from, $date_to) {
    $rows = "";
    $res = $db->query("stock_trans",
        "SELECT * FROM stock_trans
         WHERE status = 'USED'
         AND DATE(datetime_created) BETWEEN '$date_from' AND '$date_to'
         ORDER BY datetime_created DESC"
    );

    if ($res && $res->num_rows > 0) {
        while ($row = $res->fetch_assoc()) {

            $stock_res = $db->query("stock", "SELECT * FROM stock WHERE stock_no = '{$row['stock_no']}'");
            $stock     = $stock_res->fetch_assoc();

            $type_res  = $db->query("stock_types", "SELECT * FROM stock_types WHERE record_id = '{$stock['stock_type_id']}'");
            $type      = $type_res->fetch_assoc();

            $team_name = "N/A";
            if (!empty($row['order_no'])) {
                $order_res = $db->query("book_stock", "SELECT * FROM book_stock WHERE order_no = '{$row['order_no']}'");
                if ($order = $order_res->fetch_assoc()) {
                    $team_res  = $db->query("teams", "SELECT * FROM teams WHERE record_id = '{$order['team_assigned_id']}'");
                    $team      = $team_res->fetch_assoc();
                    $team_name = $team['name'] ?? "N/A";
                }
            }

            $rows .= "<tr>
                <td>" . date('Y-m-d H:i', strtotime($row['datetime_created'])) . "</td>
                <td>" . htmlspecialchars($row['order_no'] ?? 'N/A') . "</td>
                <td>" . htmlspecialchars($team_name) . "</td>
                <td>" . htmlspecialchars($type['name'] ?? 'N/A') . "</td>
                <td>" . htmlspecialchars($row['stock_no']) . "</td>
                <td>" . htmlspecialchars($row['item_name']) . "</td>
                <td>" . htmlspecialchars($row['quantity']) . "</td>
            </tr>";
        }
    } else {
        $rows = "<tr><td colspan='7' class='no-data'>NO USED STOCK FOUND FOR THIS PERIOD</td></tr>";
    }
    return $rows;
}

$week_rows  = build_rows($db, $week_start,  $week_end);
$month_rows = build_rows($db, $month_start, $month_end);
?>

<style>
    :root {
        --blue: #1e3a8a;
        --light-blue: #eaf0ff;
        --orange: #f97316;
        --orange-soft: #fde7d6;
        --white: #ffffff;
        --border: #d1d5db;
        --text: #0f172a;
    }
    body { margin: 0; background: #f8fafc; font-family: "Segoe UI", Roboto, Arial, sans-serif; color: var(--text); }
    .form_down { width: 95%; margin: auto; padding-bottom: 3vw; }
    .page-header { display: flex; justify-content: space-between; align-items: center; margin: 2.5vw 0 1.5vw; }
    h1 { font-size: 2.5vw; color: var(--blue); padding-left: 1vw; margin: 0; }
    .filter-bar { display: flex; gap: 0.8vw; margin-bottom: 1.5vw; align-items: center; }
    .filter-btn { padding: 0.5vw 1.5vw; font-size: 1vw; font-weight: 700; border-radius: 8px; border: 2px solid var(--blue); background: var(--white); color: var(--blue); cursor: pointer; transition: all 0.2s ease; }
    .filter-btn.active { background: var(--blue); color: var(--white); }
    .filter-btn:hover:not(.active) { background: var(--light-blue); }
    .period-label { font-size: 0.95vw; color: #64748b; margin-left: 0.5vw; }
    .download-btn { background: var(--orange); color: var(--white); border: none; padding: 0.6vw 1.3vw; font-size: 1vw; font-weight: 600; border-radius: 8px; cursor: pointer; box-shadow: 0 4px 10px rgba(0,0,0,0.15); transition: background 0.2s ease; text-decoration: none; display: inline-block; }
    .download-btn:hover { background: #ea580c; }
    table { width: 100%; border-collapse: collapse; background: var(--white); border-radius: 12px; overflow: hidden; box-shadow: 0 10px 30px rgba(0,0,0,0.08); }
    thead th { background: var(--blue); color: var(--white); text-align: left; padding: 1vw; font-size: 1.1vw; letter-spacing: 0.05em; }
    tbody td { padding: 0.8vw 1vw; font-size: 1vw; border-bottom: 1px solid var(--border); }
    tbody tr:nth-child(even) td { background: var(--light-blue); }
    tbody tr:hover td { background: var(--orange-soft); transition: background 0.2s ease; }
    tbody tr:last-child td { border-bottom: none; }
    .no-data { text-align: center; padding: 2vw; font-weight: 600; color: var(--blue); background: var(--light-blue); }
    .panel { display: none; }
    .panel.active { display: block; width: 95%; }
</style>

<body>
<div class="form_down">

    <div class="page-header">
        <h1>USED STOCK</h1>
    </div>

    <div class="filter-bar">
        <button class="filter-btn active" id="btn-week"  onclick="showPanel('week')">THIS WEEK</button>
        <button class="filter-btn"        id="btn-month" onclick="showPanel('month')">THIS MONTH</button>
        <span class="period-label" id="period-label">
            <?= $week_start ?> to <?= $week_end ?>
        </span>
        <div style="margin-left: auto;">
            <a id="download-link" href="used_stock_pdf.php?filter=week" class="download-btn" target="_blank">
                DOWNLOAD PDF
            </a>
        </div>
    </div>

    <div class="panel active" id="panel-week">
        <table>
            <thead>
                <tr>
                    <th>Date Used</th><th>Order No</th><th>Team</th>
                    <th>Stock Type</th><th>Stock No</th><th>Item Name</th><th>Qty Used</th>
                </tr>
            </thead>
            <tbody><?= $week_rows ?></tbody>
        </table>
    </div>

    <div class="panel" id="panel-month">
        <table>
            <thead>
                <tr>
                    <th>Date Used</th><th>Order No</th><th>Team</th>
                    <th>Stock Type</th><th>Stock No</th><th>Item Name</th><th>Qty Used</th>
                </tr>
            </thead>
            <tbody><?= $month_rows ?></tbody>
        </table>
    </div>

</div>

<script>
    const periods = {
        week:  { label: '<?= $week_start ?> to <?= $week_end ?>',   filter: 'week'  },
        month: { label: '<?= $month_start ?> to <?= $month_end ?>', filter: 'month' }
    };

    function showPanel(name) {
        document.querySelectorAll('.panel').forEach(p => p.classList.remove('active'));
        document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
        document.getElementById('panel-' + name).classList.add('active');
        document.getElementById('btn-'   + name).classList.add('active');
        document.getElementById('period-label').innerHTML = periods[name].label;
        document.getElementById('download-link').href = 'used_stock_pdf.php?filter=' + periods[name].filter;
    }
</script>
</body>