<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/DataTableRequest.php';

$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);

if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}

if ($_SESSION['role'] != 'admin' && $_SESSION['role'] != 'warehouse') {
    header('Location: /IMS/unauthorized.php');
    exit;
}

$branchId = filter_input(INPUT_GET, 'branch_id', FILTER_SANITIZE_NUMBER_INT);
if ($branchId === null || $branchId === '' || $branchId === false) {
    DataTableRequest::respond((int)($_GET['draw'] ?? 1), 0, 0, []);
}
$branchId = (int)$branchId;

$req = DataTableRequest::fromRequest();

$baseSql = "FROM sold_items s LEFT JOIN items i ON s.item_id = i.item_id WHERE s.branch_id = ?";
$baseParams = [$branchId];

$searchSql = '';
$searchParams = [];
if ($req['search'] !== null) {
    $searchSql = " AND (s.unique_code LIKE ? OR i.item_name LIKE ? OR i.item_details LIKE ? OR i.serial_number LIKE ?)";
    $term = "%{$req['search']}%";
    $searchParams = [$term, $term, $term, $term];
}

$countStmt = $conn->prepare("SELECT COUNT(*) $baseSql");
$countStmt->execute($baseParams);
$total = (int)$countStmt->fetchColumn();

$filtered = $total;
if ($req['search'] !== null) {
    $filteredStmt = $conn->prepare("SELECT COUNT(*) $baseSql$searchSql");
    $filteredStmt->execute(array_merge($baseParams, $searchParams));
    $filtered = (int)$filteredStmt->fetchColumn();
}

$sql = "SELECT s.sale_id, s.unique_code, i.item_name, i.item_details, s.unit_price, s.sold_at,
        i.warranty_months as warranty, i.serial_number, i.condition_status, s.is_verified
        $baseSql$searchSql
        ORDER BY s.sold_at DESC
        LIMIT ? OFFSET ?";
$stmt = $conn->prepare($sql);
$index = 1;
foreach (array_merge($baseParams, $searchParams) as $param) {
    $stmt->bindValue($index++, $param);
}
$stmt->bindValue($index++, $req['length'], PDO::PARAM_INT);
$stmt->bindValue($index++, $req['start'], PDO::PARAM_INT);
$stmt->execute();
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);

$data = array_map(function ($item) {
    return [
        'unique_code' => htmlspecialchars($item['unique_code'] ?? 'N/A'),
        'item_name' => htmlspecialchars($item['item_name'] ?? 'N/A'),
        'item_details' => htmlspecialchars($item['item_details'] ?? 'N/A'),
        'unit_price' => 'MWK ' . number_format((float)($item['unit_price'] ?? 0), 2),
        'condition_status' => htmlspecialchars($item['condition_status'] ?? 'N/A'),
        'warranty' => htmlspecialchars($item['warranty'] ?? '0') . ' months',
        'serial_number' => htmlspecialchars($item['serial_number'] ?? 'N/A'),
        'sold_at' => $item['sold_at'] ? date('M d, Y, g:i A', strtotime($item['sold_at'])) : 'N/A',
        'verified' => !empty($item['is_verified']) ? 'Verified' : 'Pending Verification',
    ];
}, $items);

DataTableRequest::respond($req['draw'], $total, $filtered, $data);
