<?php
require($_SERVER['DOCUMENT_ROOT'] . "/fpdf.php");
include "../../root.class.php";

$db = new db_safeguard();

$filter = isset($_GET['filter']) ? $_GET['filter'] : 'week';

if ($filter === 'month') {
    $date_from   = date('Y-m-01');
    $date_to     = date('Y-m-t');
    $period_label = date('F Y');
    $file_label   = 'Month_' . date('Y_m');
} else {
    $date_from   = date('Y-m-d', strtotime('monday this week'));
    $date_to     = date('Y-m-d', strtotime('sunday this week'));
    $period_label = 'Week: ' . $date_from . ' to ' . $date_to;
    $file_label   = 'Week_' . $date_from;
}

class PDF extends FPDF
{
    public $period = '';

    function Header()
    {
        $logo = $_SERVER['DOCUMENT_ROOT'] . '/icons/Savuki_Logo.png';
        if (file_exists($logo)) {
            $this->Image($logo, 235, 8, 50);
        }

        $this->SetFont('Arial', 'B', 18);
        $this->SetTextColor(30, 58, 138);
        $this->Cell(0, 10, 'Used Stock Report', 0, 1, 'C');

        $this->SetFont('Arial', '', 9);
        $this->SetTextColor(80, 80, 80);
        $this->Cell(0, 6, $this->period, 0, 1, 'C');

        $this->SetDrawColor(249, 115, 22);
        $this->Line(10, 26, 285, 26);

        $this->Ln(6);
    }

    function Footer()
    {
        $this->SetY(-12);
        $this->SetFont('Arial', 'I', 8);
        $this->SetTextColor(120);
        $this->Cell(0, 10, 'Generated: ' . date('Y-m-d H:i'), 0, 0, 'L');
        $this->Cell(0, 10, 'Page ' . $this->PageNo(), 0, 0, 'R');
    }
}

$pdf = new PDF();
$pdf->period = $period_label;
$pdf->AddPage('L');
$pdf->SetAutoPageBreak(true, 20);
$pdf->SetMargins(10, 15, 10);
$pdf->SetFont('Arial', 'B', 9);

/* ── Table header ── */
$pdf->SetFillColor(30, 58, 138);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(38, 8, 'Date Used',   1, 0, 'C', true);
$pdf->Cell(22, 8, 'Order No',    1, 0, 'C', true);
$pdf->Cell(30, 8, 'Team',        1, 0, 'C', true);
$pdf->Cell(50, 8, 'Stock Type',  1, 0, 'C', true);
$pdf->Cell(20, 8, 'Stock No',    1, 0, 'C', true);
$pdf->Cell(80, 8, 'Item Name',   1, 0, 'C', true);
$pdf->Cell(20, 8, 'Qty Used',    1, 1, 'C', true);

/* ── Data rows ── */
$pdf->SetFont('Arial', '', 9);
$pdf->SetTextColor(40, 40, 40);

$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"
);

$fill = false;

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";
            }
        }

        $pdf->SetFillColor($fill ? 234 : 255, $fill ? 240 : 255, 255);

        $pdf->Cell(38, 8, date('Y-m-d H:i', strtotime($row['datetime_created'])), 1, 0, 'L', $fill);
        $pdf->Cell(22, 8, $row['order_no'] ?? 'N/A',   1, 0, 'L', $fill);
        $pdf->Cell(30, 8, $team_name,                  1, 0, 'L', $fill);
        $pdf->Cell(50, 8, $type['name'] ?? 'N/A',      1, 0, 'L', $fill);
        $pdf->Cell(20, 8, $row['stock_no'],             1, 0, 'C', $fill);
        $pdf->Cell(80, 8, $row['item_name'],            1, 0, 'L', $fill);
        $pdf->Cell(20, 8, $row['quantity'],             1, 1, 'C', $fill);

        $fill = !$fill;
    }

} else {

    $pdf->SetFont('Arial', 'B', 11);
    $pdf->SetTextColor(30, 58, 138);
    $pdf->Cell(0, 12, 'NO USED STOCK FOUND FOR THIS PERIOD', 1, 1, 'C');
}

$pdf->Output('I', 'Used_Stock_' . $file_label . '_' . date('Ymd_His') . '.pdf');