<?php
require_once '../../vendor/autoload.php';
require_once '../../classes/Database.php';
require_once '../../classes/StockTaking.php';
require_once '../../classes/Branding.php';


session_start();
require_once '../../includes/auth.php';
$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);

if (!$auth->isSuperAdmin($_SESSION['user_id']) &&
    !$auth->isWarehousePersonnel($_SESSION['user_id']) &&
    !$auth->isBranchManager($_SESSION['user_id'])) {
    header('Location: /unauthorized.php');
    exit;
}


$sessionId = isset($_GET['session_id']) ? (int)$_GET['session_id'] : 0;
if (!$sessionId) {
    die('Invalid session ID');
}


if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
    $userBranch = $auth->getUserBranch($_SESSION['user_id']);
    $sessionSql = "SELECT branch_id FROM stock_taking_sessions WHERE session_id = :session_id";
    $sessionStmt = $conn->prepare($sessionSql);
    $sessionStmt->bindValue(':session_id', $sessionId, PDO::PARAM_INT);
    $sessionStmt->execute();
    $session = $sessionStmt->fetch(PDO::FETCH_ASSOC);

    if (!$session || $session['branch_id'] != $userBranch) {
        die('Access denied: You can only access reports for your own branch.');
    }
}


$stockTaking = new StockTaking($conn);
$report = $stockTaking->getSessionReport($sessionId);

if (isset($report['error'])) {
    die('Error: ' . $report['error']);
}

$session = $report['session'];
$summary = $report['summary'];
$sessionBranding = Branding::documentDetailsForBranchId($conn, (int)($session['branch_id'] ?? 0));


$itemSummary = $stockTaking->getItemQuantitySummary($sessionId);


$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);


$pdf->SetCreator($sessionBranding['name']);
$pdf->SetAuthor($sessionBranding['name']);
$pdf->SetTitle('Stock Taking Report - Session ' . $sessionId);
$pdf->SetSubject('Stock Taking Report');


$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);


$pdf->SetMargins(15, 15, 15);
$pdf->SetAutoPageBreak(TRUE, 15);


$pdf->AddPage();

$sessionLogoFile = (string)($sessionBranding['logo_file'] ?? '');
if ($sessionLogoFile !== '' && (preg_match('/^https?:\/\//i', $sessionLogoFile) || is_file($sessionLogoFile))) {
    $pdf->Image($sessionLogoFile, 15, 10, 25, 15, '', '', '', true, 300, '', false, false, 0, 'CM');
}
$pdf->SetXY(45, 10);
$pdf->SetFont('helvetica', 'B', 13);
$pdf->Cell(0, 7, (string)$sessionBranding['name'], 0, 1, 'L');
$pdf->SetX(45);
$pdf->SetFont('helvetica', '', 8);
$pdf->MultiCell(0, 5, Branding::contactLine($sessionBranding), 0, 'L', false, 1);
$pdf->SetY(max($pdf->GetY() + 3, 30));


$pdf->SetFont('helvetica', 'B', 16);


$pdf->Cell(0, 10, 'Stock Taking Report', 0, 1, 'C');
$pdf->Ln(5);


$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(0, 8, 'Session Information', 0, 1, 'L');
$pdf->SetFont('helvetica', '', 10);

$pdf->Cell(50, 6, 'Branch:', 0, 0);
$pdf->Cell(0, 6, $session['branch_name'], 0, 1);

$pdf->Cell(50, 6, 'Date:', 0, 0);
$pdf->Cell(0, 6, date('F j, Y', strtotime($session['session_date'])), 0, 1);

$pdf->Cell(50, 6, 'Auditor:', 0, 0);
$pdf->Cell(0, 6, $session['auditor_name'], 0, 1);

$pdf->Cell(50, 6, 'Status:', 0, 0);
$pdf->Cell(0, 6, 'Completed', 0, 1);

$pdf->Cell(50, 6, 'Completed:', 0, 0);
$pdf->Cell(0, 6, date('F j, Y \a\t g:i A', strtotime($session['completed_at'])), 0, 1);

$pdf->Ln(5);


$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(0, 8, 'Summary', 0, 1, 'L');
$pdf->SetFont('helvetica', '', 10);

$pdf->Cell(40, 6, 'Total System Items:', 0, 0);
$pdf->Cell(20, 6, $summary['total_system'], 0, 0, 'R');
$pdf->Cell(40, 6, 'Items Found:', 0, 0);
$pdf->Cell(20, 6, $summary['total_found'], 0, 1, 'R');

$pdf->Cell(40, 6, 'Items Missing:', 0, 0);
$pdf->Cell(20, 6, $summary['total_missing'], 0, 0, 'R');
$pdf->Cell(40, 6, 'Extra Items:', 0, 0);
$pdf->Cell(20, 6, $summary['total_extra'], 0, 1, 'R');

$pdf->Ln(5);


if (!isset($itemSummary['error']) && !empty($itemSummary)) {
    $pdf->SetFont('helvetica', 'B', 12);
    $pdf->Cell(0, 8, 'Item Quantity Summary by Name', 0, 1, 'L');
    $pdf->SetFont('helvetica', '', 8);


    $pdf->SetFillColor(220, 230, 255);
    $pdf->Cell(50, 6, 'Item Name', 1, 0, 'L', true);
    $pdf->Cell(15, 6, 'Total', 1, 0, 'C', true);
    $pdf->Cell(15, 6, 'Found', 1, 0, 'C', true);
    $pdf->Cell(15, 6, 'Missing', 1, 0, 'C', true);
    $pdf->Cell(15, 6, 'Extra', 1, 0, 'C', true);
    $pdf->Cell(20, 6, 'Progress', 1, 1, 'C', true);


    foreach ($itemSummary as $item) {
        $y = $pdf->GetY();
        if ($y > 250) {
            $pdf->AddPage();
            $pdf->SetFont('helvetica', 'B', 12);
            $pdf->Cell(0, 8, 'Item Quantity Summary (continued)', 0, 1, 'L');
            $pdf->SetFont('helvetica', '', 8);


            $pdf->SetFillColor(220, 230, 255);
            $pdf->Cell(50, 6, 'Item Name', 1, 0, 'L', true);
            $pdf->Cell(15, 6, 'Total', 1, 0, 'C', true);
            $pdf->Cell(15, 6, 'Found', 1, 0, 'C', true);
            $pdf->Cell(15, 6, 'Missing', 1, 0, 'C', true);
            $pdf->Cell(15, 6, 'Extra', 1, 0, 'C', true);
            $pdf->Cell(20, 6, 'Progress', 1, 1, 'C', true);
        }

        $itemName = trim((string)$item['item_name'] . ' - ' . (string)($item['item_details'] ?? 'N/A'));
        $total = $item['total_system_quantity'];
        $found = $item['found_quantity'] ?? 0;
        $missing = $item['missing_quantity'] ?? 0;
        $extra = $item['extra_quantity'] ?? 0;
        $progress = $total > 0 ? round(($found + $missing) / $total * 100, 1) : 0;


        $itemName = strlen($itemName) > 25 ? substr($itemName, 0, 22) . '...' : $itemName;

        $pdf->Cell(50, 5, $itemName, 1, 0, 'L');
        $pdf->Cell(15, 5, $total, 1, 0, 'C');
        $pdf->Cell(15, 5, $found, 1, 0, 'C');
        $pdf->Cell(15, 5, $missing, 1, 0, 'C');
        $pdf->Cell(15, 5, $extra, 1, 0, 'C');
        $pdf->Cell(20, 5, $progress . '%', 1, 1, 'C');
    }

    $pdf->Ln(5);
}


if (!empty($report['found_items'])) {
    $pdf->SetFont('helvetica', 'B', 12);
    $pdf->Cell(0, 8, 'Found Items (' . count($report['found_items']) . ')', 0, 1, 'L');
    $pdf->SetFont('helvetica', '', 9);


    $pdf->SetFillColor(200, 220, 255);
    $pdf->Cell(60, 7, 'Item Name', 1, 0, 'L', true);
    $pdf->Cell(30, 7, 'Unique Code', 1, 0, 'L', true);
    $pdf->Cell(40, 7, 'Location Found', 1, 0, 'L', true);
    $pdf->Cell(50, 7, 'Notes', 1, 1, 'L', true);


    foreach ($report['found_items'] as $item) {
        $y = $pdf->GetY();
        if ($y > 250) {
            $pdf->AddPage();
            $pdf->SetFont('helvetica', 'B', 12);
            $pdf->Cell(0, 8, 'Found Items (continued)', 0, 1, 'L');
            $pdf->SetFont('helvetica', '', 9);


            $pdf->SetFillColor(200, 220, 255);
            $pdf->Cell(60, 7, 'Item Name', 1, 0, 'L', true);
            $pdf->Cell(30, 7, 'Unique Code', 1, 0, 'L', true);
            $pdf->Cell(40, 7, 'Location Found', 1, 0, 'L', true);
            $pdf->Cell(50, 7, 'Notes', 1, 1, 'L', true);
        }

        $itemName = trim((string)($item['item_name'] ?? 'Unknown Item') . ' - ' . (string)($item['item_details'] ?? 'N/A'));
        $uniqueCode = $item['unique_code'];
        $location = $item['location_found'] ?? '';
        $notes = $item['notes'] ?? '';


        $itemName = strlen($itemName) > 25 ? substr($itemName, 0, 22) . '...' : $itemName;
        $location = strlen($location) > 18 ? substr($location, 0, 15) . '...' : $location;
        $notes = strlen($notes) > 22 ? substr($notes, 0, 19) . '...' : $notes;

        $pdf->Cell(60, 6, $itemName, 1, 0, 'L');
        $pdf->Cell(30, 6, $uniqueCode, 1, 0, 'L');
        $pdf->Cell(40, 6, $location, 1, 0, 'L');
        $pdf->Cell(50, 6, $notes, 1, 1, 'L');
    }

    $pdf->Ln(5);
}


if (!empty($report['missing_items'])) {
    if (!empty($report['found_items'])) {
        $pdf->AddPage();
    }

    $pdf->SetFont('helvetica', 'B', 12);
    $pdf->Cell(0, 8, 'Missing Items (' . count($report['missing_items']) . ')', 0, 1, 'L');
    $pdf->SetFont('helvetica', '', 9);


    $pdf->SetFillColor(255, 200, 200);
    $pdf->Cell(60, 7, 'Item Name', 1, 0, 'L', true);
    $pdf->Cell(30, 7, 'Unique Code', 1, 0, 'L', true);
    $pdf->Cell(40, 7, 'Last Known Location', 1, 0, 'L', true);
    $pdf->Cell(50, 7, 'Notes', 1, 1, 'L', true);


    foreach ($report['missing_items'] as $item) {
        $y = $pdf->GetY();
        if ($y > 250) {
            $pdf->AddPage();
            $pdf->SetFont('helvetica', 'B', 12);
            $pdf->Cell(0, 8, 'Missing Items (continued)', 0, 1, 'L');
            $pdf->SetFont('helvetica', '', 9);


            $pdf->SetFillColor(255, 200, 200);
            $pdf->Cell(60, 7, 'Item Name', 1, 0, 'L', true);
            $pdf->Cell(30, 7, 'Unique Code', 1, 0, 'L', true);
            $pdf->Cell(40, 7, 'Last Known Location', 1, 0, 'L', true);
            $pdf->Cell(50, 7, 'Notes', 1, 1, 'L', true);
        }

        $itemName = trim((string)($item['item_name'] ?? 'Unknown Item') . ' - ' . (string)($item['item_details'] ?? 'N/A'));
        $uniqueCode = $item['unique_code'];
        $location = $item['location_found'] ?? '';
        $notes = $item['notes'] ?? '';


        $itemName = strlen($itemName) > 25 ? substr($itemName, 0, 22) . '...' : $itemName;
        $location = strlen($location) > 18 ? substr($location, 0, 15) . '...' : $location;
        $notes = strlen($notes) > 22 ? substr($notes, 0, 19) . '...' : $notes;

        $pdf->Cell(60, 6, $itemName, 1, 0, 'L');
        $pdf->Cell(30, 6, $uniqueCode, 1, 0, 'L');
        $pdf->Cell(40, 6, $location, 1, 0, 'L');
        $pdf->Cell(50, 6, $notes, 1, 1, 'L');
    }
}


if (!empty($session['notes'])) {
    $pdf->Ln(10);
    $pdf->SetFont('helvetica', 'B', 12);
    $pdf->Cell(0, 8, 'Session Notes', 0, 1, 'L');
    $pdf->SetFont('helvetica', '', 10);
    $pdf->MultiCell(0, 6, $session['notes'], 0, 'L');
}


$filename = 'stock_taking_report_' . $sessionId . '_' . date('Y-m-d') . '.pdf';
$pdf->Output($filename, 'D');
?>
