<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Inventory Month-End Closing Report';

if (!function_exists('h')) {
    function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('money_fmt')) {
    function money_fmt($amount): string { return number_format((float)$amount, 2); }
}

$errors = [];

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS store_locations (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        location_code VARCHAR(50) NULL,
        location_name VARCHAR(150) NOT NULL,
        location_type ENUM('main_store','bar','restaurant','curio','kitchen','housekeeping','maintenance','other') NOT NULL DEFAULT 'main_store',
        is_pos_location TINYINT(1) NOT NULL DEFAULT 0,
        allow_room_charge TINYINT(1) NOT NULL DEFAULT 1,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        notes TEXT NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_store_location_code (location_code)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS inventory_item_categories (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        category_name VARCHAR(120) NOT NULL,
        category_type ENUM('stock','food','bar','curio','consumable','service','other') NOT NULL DEFAULT 'stock',
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_inventory_category_name (category_name)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS inventory_units (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        unit_code VARCHAR(30) NOT NULL,
        unit_name VARCHAR(80) NOT NULL,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY uq_inventory_unit_code (unit_code)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS inventory_items (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        item_code VARCHAR(60) NULL,
        item_name VARCHAR(180) NOT NULL,
        category_id INT UNSIGNED NULL,
        unit_id INT UNSIGNED NULL,
        item_type ENUM('stock','food','bar','curio','consumable','service','recipe','other') NOT NULL DEFAULT 'stock',
        barcode VARCHAR(100) NULL,
        description TEXT NULL,
        cost_price DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        avg_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        selling_price DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        tax_rate DECIMAL(7,4) NOT NULL DEFAULT 0.0000,
        reorder_level DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        reorder_qty DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        is_stock_item TINYINT(1) NOT NULL DEFAULT 1,
        is_pos_item TINYINT(1) NOT NULL DEFAULT 0,
        allow_room_charge TINYINT(1) NOT NULL DEFAULT 1,
        track_expiry TINYINT(1) NOT NULL DEFAULT 0,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_inventory_item_code (item_code),
        INDEX idx_inventory_item_name (item_name)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS stock_movements (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        item_id INT UNSIGNED NOT NULL,
        store_id INT UNSIGNED NOT NULL,
        movement_type ENUM('OPENING','GRN','ISSUE','SALE','TRANSFER_IN','TRANSFER_OUT','ADJUSTMENT_IN','ADJUSTMENT_OUT','WASTAGE','RETURN') NOT NULL,
        qty_in DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        qty_out DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        unit_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        total_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        reference_type VARCHAR(60) NULL,
        reference_id BIGINT UNSIGNED NULL,
        notes TEXT NULL,
        movement_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_stock_item_store (item_id, store_id),
        INDEX idx_stock_movement_date (movement_date),
        INDEX idx_stock_reference (reference_type, reference_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS inventory_month_closings (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        closing_month CHAR(7) NOT NULL,
        store_id INT UNSIGNED NULL,
        status ENUM('draft','closed','reopened') NOT NULL DEFAULT 'draft',
        opening_value DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        movement_in_value DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        movement_out_value DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        closing_value DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        notes TEXT NULL,
        closed_by INT UNSIGNED NULL,
        closed_at DATETIME NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_month_store (closing_month, store_id),
        INDEX idx_closing_month (closing_month)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Throwable $e) {
    $errors[] = 'Could not prepare month-end closing tables: ' . $e->getMessage();
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (function_exists('verify_csrf')) verify_csrf();

        $action = (string)($_POST['action'] ?? '');
        $closingMonth = trim((string)($_POST['closing_month'] ?? date('Y-m')));
        $storeIdPost = (int)($_POST['store_id'] ?? 0);
        $notes = trim((string)($_POST['notes'] ?? ''));

        if (!preg_match('/^\d{4}-\d{2}$/', $closingMonth)) {
            throw new RuntimeException('Invalid closing month.');
        }

        $monthStart = $closingMonth . '-01 00:00:00';
        $monthEnd = date('Y-m-t 23:59:59', strtotime($closingMonth . '-01'));

        if ($action === 'close_month') {
            $storeFilter = $storeIdPost > 0 ? " AND sm.store_id = :store_id" : "";
            $params = [':month_start' => $monthStart, ':month_end' => $monthEnd];
            if ($storeIdPost > 0) $params[':store_id'] = $storeIdPost;

            $stmt = $pdo->prepare("
                SELECT
                    COALESCE(SUM(CASE WHEN sm.movement_date < :month_start THEN (sm.qty_in - sm.qty_out) * sm.unit_cost ELSE 0 END),0) AS opening_value,
                    COALESCE(SUM(CASE WHEN sm.movement_date BETWEEN :month_start AND :month_end THEN sm.qty_in * sm.unit_cost ELSE 0 END),0) AS movement_in_value,
                    COALESCE(SUM(CASE WHEN sm.movement_date BETWEEN :month_start AND :month_end THEN sm.qty_out * sm.unit_cost ELSE 0 END),0) AS movement_out_value,
                    COALESCE(SUM(CASE WHEN sm.movement_date <= :month_end THEN (sm.qty_in - sm.qty_out) * sm.unit_cost ELSE 0 END),0) AS closing_value
                FROM stock_movements sm
                WHERE 1=1 $storeFilter
            ");
            $stmt->execute($params);
            $tot = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

            $stmt = $pdo->prepare("
                INSERT INTO inventory_month_closings
                (closing_month, store_id, status, opening_value, movement_in_value, movement_out_value, closing_value, notes, closed_by, closed_at)
                VALUES
                (:closing_month, :store_id, 'closed', :opening_value, :movement_in_value, :movement_out_value, :closing_value, :notes, :closed_by, NOW())
                ON DUPLICATE KEY UPDATE
                    status='closed',
                    opening_value=VALUES(opening_value),
                    movement_in_value=VALUES(movement_in_value),
                    movement_out_value=VALUES(movement_out_value),
                    closing_value=VALUES(closing_value),
                    notes=VALUES(notes),
                    closed_by=VALUES(closed_by),
                    closed_at=NOW()
            ");
            $stmt->execute([
                ':closing_month' => $closingMonth,
                ':store_id' => $storeIdPost > 0 ? $storeIdPost : null,
                ':opening_value' => (float)($tot['opening_value'] ?? 0),
                ':movement_in_value' => (float)($tot['movement_in_value'] ?? 0),
                ':movement_out_value' => (float)($tot['movement_out_value'] ?? 0),
                ':closing_value' => (float)($tot['closing_value'] ?? 0),
                ':notes' => $notes ?: null,
                ':closed_by' => $_SESSION['user_id'] ?? null,
            ]);

            $_SESSION['month_close_flash'] = ['success', 'Month closed successfully.'];
            header('Location: month_end_inventory_report.php?closing_month=' . urlencode($closingMonth) . '&store_id=' . $storeIdPost);
            exit;
        }

        if ($action === 'reopen_month') {
            $stmt = $pdo->prepare("
                UPDATE inventory_month_closings
                SET status='reopened',
                    notes = CONCAT(COALESCE(notes,''), '\nReopened: ', :notes)
                WHERE closing_month = :closing_month
                  AND ((:store_id = 0 AND store_id IS NULL) OR store_id = :store_id)
            ");
            $stmt->execute([
                ':notes' => $notes ?: 'No reason supplied',
                ':closing_month' => $closingMonth,
                ':store_id' => $storeIdPost,
            ]);

            $_SESSION['month_close_flash'] = ['warning', 'Month reopened.'];
            header('Location: month_end_inventory_report.php?closing_month=' . urlencode($closingMonth) . '&store_id=' . $storeIdPost);
            exit;
        }

    } catch (Throwable $e) {
        $_SESSION['month_close_flash'] = ['danger', $e->getMessage()];
        header('Location: month_end_inventory_report.php');
        exit;
    }
}

$flash = $_SESSION['month_close_flash'] ?? null;
unset($_SESSION['month_close_flash']);

$stores = [];
$categories = [];

try {
    $stores = $pdo->query("SELECT * FROM store_locations WHERE is_active=1 ORDER BY location_name ASC")->fetchAll(PDO::FETCH_ASSOC);
    $categories = $pdo->query("SELECT * FROM inventory_item_categories WHERE is_active=1 ORDER BY category_name ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $errors[] = 'Could not load filters: ' . $e->getMessage();
}

$closingMonth = trim((string)($_GET['closing_month'] ?? date('Y-m')));
$storeId = (int)($_GET['store_id'] ?? 0);
$categoryId = (int)($_GET['category_id'] ?? 0);
$search = trim((string)($_GET['q'] ?? ''));

if (!preg_match('/^\d{4}-\d{2}$/', $closingMonth)) $closingMonth = date('Y-m');

$monthStartDate = $closingMonth . '-01';
$monthEndDate = date('Y-m-t', strtotime($monthStartDate));
$monthStart = $monthStartDate . ' 00:00:00';
$monthEnd = $monthEndDate . ' 23:59:59';

$where = "ii.is_stock_item = 1";
$params = [':month_start' => $monthStart, ':month_end' => $monthEnd];

if ($storeId > 0) { $where .= " AND sl.id = :store_id"; $params[':store_id'] = $storeId; }
if ($categoryId > 0) { $where .= " AND ii.category_id = :category_id"; $params[':category_id'] = $categoryId; }
if ($search !== '') {
    $where .= " AND (ii.item_name LIKE :q OR ii.item_code LIKE :q OR c.category_name LIKE :q OR sl.location_name LIKE :q)";
    $params[':q'] = '%' . $search . '%';
}

$rows = [];
$summary = [
    'opening_qty' => 0,
    'opening_value' => 0,
    'in_qty' => 0,
    'in_value' => 0,
    'out_qty' => 0,
    'out_value' => 0,
    'closing_qty' => 0,
    'closing_value' => 0,
    'sales_qty' => 0,
    'sales_value' => 0,
    'wastage_qty' => 0,
    'wastage_value' => 0,
    'adjustment_net_value' => 0,
];

try {
    $stmt = $pdo->prepare("
        SELECT
            ii.id AS item_id,
            ii.item_code,
            ii.item_name,
            ii.avg_cost,
            ii.cost_price,
            ii.reorder_level,
            c.category_name,
            u.unit_code,
            sl.id AS store_id,
            sl.location_name,

            COALESCE(SUM(CASE WHEN sm.movement_date < :month_start THEN sm.qty_in - sm.qty_out ELSE 0 END),0) AS opening_qty,
            COALESCE(SUM(CASE WHEN sm.movement_date < :month_start THEN (sm.qty_in - sm.qty_out) * sm.unit_cost ELSE 0 END),0) AS opening_value,

            COALESCE(SUM(CASE WHEN sm.movement_date BETWEEN :month_start AND :month_end THEN sm.qty_in ELSE 0 END),0) AS in_qty,
            COALESCE(SUM(CASE WHEN sm.movement_date BETWEEN :month_start AND :month_end THEN sm.qty_in * sm.unit_cost ELSE 0 END),0) AS in_value,

            COALESCE(SUM(CASE WHEN sm.movement_date BETWEEN :month_start AND :month_end THEN sm.qty_out ELSE 0 END),0) AS out_qty,
            COALESCE(SUM(CASE WHEN sm.movement_date BETWEEN :month_start AND :month_end THEN sm.qty_out * sm.unit_cost ELSE 0 END),0) AS out_value,

            COALESCE(SUM(CASE WHEN sm.movement_date <= :month_end THEN sm.qty_in - sm.qty_out ELSE 0 END),0) AS closing_qty,
            COALESCE(SUM(CASE WHEN sm.movement_date <= :month_end THEN (sm.qty_in - sm.qty_out) * sm.unit_cost ELSE 0 END),0) AS closing_value,

            COALESCE(SUM(CASE WHEN sm.movement_date BETWEEN :month_start AND :month_end AND sm.movement_type='GRN' THEN sm.qty_in ELSE 0 END),0) AS grn_qty,
            COALESCE(SUM(CASE WHEN sm.movement_date BETWEEN :month_start AND :month_end AND sm.movement_type='GRN' THEN sm.qty_in * sm.unit_cost ELSE 0 END),0) AS grn_value,

            COALESCE(SUM(CASE WHEN sm.movement_date BETWEEN :month_start AND :month_end AND sm.movement_type='SALE' THEN sm.qty_out ELSE 0 END),0) AS sale_qty,
            COALESCE(SUM(CASE WHEN sm.movement_date BETWEEN :month_start AND :month_end AND sm.movement_type='SALE' THEN sm.qty_out * sm.unit_cost ELSE 0 END),0) AS sale_value,

            COALESCE(SUM(CASE WHEN sm.movement_date BETWEEN :month_start AND :month_end AND sm.movement_type='WASTAGE' THEN sm.qty_out ELSE 0 END),0) AS wastage_qty,
            COALESCE(SUM(CASE WHEN sm.movement_date BETWEEN :month_start AND :month_end AND sm.movement_type='WASTAGE' THEN sm.qty_out * sm.unit_cost ELSE 0 END),0) AS wastage_value,

            COALESCE(SUM(CASE WHEN sm.movement_date BETWEEN :month_start AND :month_end AND sm.movement_type='ADJUSTMENT_IN' THEN sm.qty_in * sm.unit_cost ELSE 0 END),0) -
            COALESCE(SUM(CASE WHEN sm.movement_date BETWEEN :month_start AND :month_end AND sm.movement_type='ADJUSTMENT_OUT' THEN sm.qty_out * sm.unit_cost ELSE 0 END),0) AS adjustment_net_value,

            COALESCE(SUM(CASE WHEN sm.movement_date BETWEEN :month_start AND :month_end AND sm.movement_type='TRANSFER_IN' THEN sm.qty_in ELSE 0 END),0) AS transfer_in_qty,
            COALESCE(SUM(CASE WHEN sm.movement_date BETWEEN :month_start AND :month_end AND sm.movement_type='TRANSFER_OUT' THEN sm.qty_out ELSE 0 END),0) AS transfer_out_qty
        FROM inventory_items ii
        CROSS JOIN store_locations sl
        LEFT JOIN inventory_item_categories c ON c.id = ii.category_id
        LEFT JOIN inventory_units u ON u.id = ii.unit_id
        LEFT JOIN stock_movements sm ON sm.item_id = ii.id AND sm.store_id = sl.id
        WHERE $where
          AND sl.is_active = 1
        GROUP BY ii.id, sl.id
        HAVING ABS(opening_qty) > 0.0001
            OR ABS(in_qty) > 0.0001
            OR ABS(out_qty) > 0.0001
            OR ABS(closing_qty) > 0.0001
        ORDER BY sl.location_name ASC, c.category_name ASC, ii.item_name ASC
        LIMIT 3000
    ");
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($rows as $row) {
        $summary['opening_qty'] += (float)$row['opening_qty'];
        $summary['opening_value'] += (float)$row['opening_value'];
        $summary['in_qty'] += (float)$row['in_qty'];
        $summary['in_value'] += (float)$row['in_value'];
        $summary['out_qty'] += (float)$row['out_qty'];
        $summary['out_value'] += (float)$row['out_value'];
        $summary['closing_qty'] += (float)$row['closing_qty'];
        $summary['closing_value'] += (float)$row['closing_value'];
        $summary['sales_qty'] += (float)$row['sale_qty'];
        $summary['sales_value'] += (float)$row['sale_value'];
        $summary['wastage_qty'] += (float)$row['wastage_qty'];
        $summary['wastage_value'] += (float)$row['wastage_value'];
        $summary['adjustment_net_value'] += (float)$row['adjustment_net_value'];
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load month-end report: ' . $e->getMessage();
}

$storeTotals = [];
$categoryTotals = [];

foreach ($rows as $row) {
    $store = $row['location_name'] ?: 'Store';
    $cat = $row['category_name'] ?: 'Uncategorised';

    if (!isset($storeTotals[$store])) $storeTotals[$store] = ['opening'=>0,'in'=>0,'out'=>0,'closing'=>0,'sales'=>0,'wastage'=>0];
    $storeTotals[$store]['opening'] += (float)$row['opening_value'];
    $storeTotals[$store]['in'] += (float)$row['in_value'];
    $storeTotals[$store]['out'] += (float)$row['out_value'];
    $storeTotals[$store]['closing'] += (float)$row['closing_value'];
    $storeTotals[$store]['sales'] += (float)$row['sale_value'];
    $storeTotals[$store]['wastage'] += (float)$row['wastage_value'];

    if (!isset($categoryTotals[$cat])) $categoryTotals[$cat] = ['opening'=>0,'in'=>0,'out'=>0,'closing'=>0,'sales'=>0,'wastage'=>0];
    $categoryTotals[$cat]['opening'] += (float)$row['opening_value'];
    $categoryTotals[$cat]['in'] += (float)$row['in_value'];
    $categoryTotals[$cat]['out'] += (float)$row['out_value'];
    $categoryTotals[$cat]['closing'] += (float)$row['closing_value'];
    $categoryTotals[$cat]['sales'] += (float)$row['sale_value'];
    $categoryTotals[$cat]['wastage'] += (float)$row['wastage_value'];
}

$closingRecord = null;
try {
    $stmt = $pdo->prepare("
        SELECT mc.*, sl.location_name
        FROM inventory_month_closings mc
        LEFT JOIN store_locations sl ON sl.id = mc.store_id
        WHERE mc.closing_month = :closing_month
          AND ((:store_id = 0 AND mc.store_id IS NULL) OR mc.store_id = :store_id)
        LIMIT 1
    ");
    $stmt->execute([':closing_month' => $closingMonth, ':store_id' => $storeId]);
    $closingRecord = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
} catch (Throwable $e) {}

$expectedClosing = $summary['opening_value'] + $summary['in_value'] - $summary['out_value'];
$variance = $summary['closing_value'] - $expectedClosing;

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band no-print">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-calendar-check"></i> Inventory Reports</div>
            <div class="hero-title mt-2">Inventory Month-End Closing</div>
            <div class="hero-subtitle mt-2">Opening stock, purchases, transfers, sales, adjustments, wastage and closing stock value.</div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <button onclick="window.print()" class="btn btn-light me-2"><i class="bi bi-printer me-2"></i>Print</button>
            <a href="inventory_dashboard.php" class="btn btn-outline-light"><i class="bi bi-speedometer2 me-2"></i>Dashboard</a>
        </div>
    </div>
</div>

<?php if ($flash): ?>
    <div class="alert alert-<?php echo h($flash[0]); ?> no-print"><?php echo h($flash[1]); ?></div>
<?php endif; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger no-print">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0"><?php foreach ($errors as $err): ?><li><?php echo h($err); ?></li><?php endforeach; ?></ul>
    </div>
<?php endif; ?>

<div class="print-title">
    <h3 class="mb-1">Inventory Month-End Closing Report</h3>
    <div class="text-muted"><?php echo h(date('F Y', strtotime($monthStartDate))); ?></div>
</div>

<div class="card panel-card mb-4 no-print">
    <div class="card-body">
        <form method="get" class="row g-3 align-items-end">
            <div class="col-md-2"><label class="form-label">Month</label><input type="month" name="closing_month" class="form-control" value="<?php echo h($closingMonth); ?>"></div>
            <div class="col-md-3"><label class="form-label">Store</label><select name="store_id" class="form-select"><option value="0">All stores consolidated</option><?php foreach ($stores as $store): ?><option value="<?php echo (int)$store['id']; ?>" <?php echo $storeId === (int)$store['id'] ? 'selected' : ''; ?>><?php echo h($store['location_name']); ?></option><?php endforeach; ?></select></div>
            <div class="col-md-2"><label class="form-label">Category</label><select name="category_id" class="form-select"><option value="0">All categories</option><?php foreach ($categories as $cat): ?><option value="<?php echo (int)$cat['id']; ?>" <?php echo $categoryId === (int)$cat['id'] ? 'selected' : ''; ?>><?php echo h($cat['category_name']); ?></option><?php endforeach; ?></select></div>
            <div class="col-md-3"><label class="form-label">Search</label><input type="text" name="q" class="form-control" value="<?php echo h($search); ?>" placeholder="Item/code/store/category"></div>
            <div class="col-md-2 d-grid"><button class="btn btn-primary"><i class="bi bi-funnel me-2"></i>Apply</button></div>
        </form>
    </div>
</div>

<?php if ($closingRecord): ?>
    <div class="alert <?php echo $closingRecord['status'] === 'closed' ? 'alert-success' : 'alert-warning'; ?> no-print">
        <strong>Status:</strong> <?php echo h(ucwords($closingRecord['status'])); ?>
        <?php if (!empty($closingRecord['closed_at'])): ?> • Closed at <?php echo h($closingRecord['closed_at']); ?><?php endif; ?>
        <?php if (!empty($closingRecord['notes'])): ?><br><?php echo nl2br(h($closingRecord['notes'])); ?><?php endif; ?>
    </div>
<?php else: ?>
    <div class="alert alert-info no-print">This month is not yet closed.</div>
<?php endif; ?>

<div class="row g-4 mb-4">
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-box-arrow-in-right"></i></div><div><div class="metric-label">Opening Value</div><div class="metric-value small-value"><?php echo money_fmt($summary['opening_value']); ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-success-subtle text-success"><i class="bi bi-arrow-down-circle"></i></div><div><div class="metric-label">Stock In</div><div class="metric-value small-value"><?php echo money_fmt($summary['in_value']); ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-danger-subtle text-danger"><i class="bi bi-arrow-up-circle"></i></div><div><div class="metric-label">Stock Out</div><div class="metric-value small-value"><?php echo money_fmt($summary['out_value']); ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-safe"></i></div><div><div class="metric-label">Closing Value</div><div class="metric-value small-value"><?php echo money_fmt($summary['closing_value']); ?></div></div></div></div>
</div>

<div class="row g-4 mb-4">
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-info-subtle text-info"><i class="bi bi-cash-register"></i></div><div><div class="metric-label">POS Cost/Sales Out</div><div class="metric-value small-value"><?php echo money_fmt($summary['sales_value']); ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-dark-subtle text-dark"><i class="bi bi-trash3"></i></div><div><div class="metric-label">Wastage Value</div><div class="metric-value small-value"><?php echo money_fmt($summary['wastage_value']); ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-secondary-subtle text-secondary"><i class="bi bi-sliders"></i></div><div><div class="metric-label">Adjustment Net</div><div class="metric-value small-value"><?php echo money_fmt($summary['adjustment_net_value']); ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon <?php echo abs($variance) > 0.01 ? 'bg-danger-subtle text-danger' : 'bg-success-subtle text-success'; ?>"><i class="bi bi-balance-scale"></i></div><div><div class="metric-label">Formula Variance</div><div class="metric-value small-value"><?php echo money_fmt($variance); ?></div></div></div></div>
</div>

<div class="card panel-card mb-4 no-print">
    <div class="card-header"><h5 class="mb-0">Closing Actions</h5></div>
    <div class="card-body">
        <div class="row g-3">
            <div class="col-lg-7">
                <div class="alert alert-light border mb-0">
                    <strong>Formula check:</strong> Opening + Stock In - Stock Out = Expected Closing.
                    Expected Closing: <strong><?php echo money_fmt($expectedClosing); ?></strong>.
                    Actual Closing: <strong><?php echo money_fmt($summary['closing_value']); ?></strong>.
                </div>
            </div>
            <div class="col-lg-5">
                <?php if (!$closingRecord || $closingRecord['status'] !== 'closed'): ?>
                    <form method="post" onsubmit="return confirm('Close this month? This stores a snapshot total for the selected store/month.');">
                        <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                        <input type="hidden" name="action" value="close_month">
                        <input type="hidden" name="closing_month" value="<?php echo h($closingMonth); ?>">
                        <input type="hidden" name="store_id" value="<?php echo (int)$storeId; ?>">
                        <div class="input-group"><input type="text" name="notes" class="form-control" placeholder="Closing notes"><button class="btn btn-success"><i class="bi bi-lock me-1"></i>Close Month</button></div>
                    </form>
                <?php else: ?>
                    <form method="post" onsubmit="return confirm('Reopen this month?');">
                        <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                        <input type="hidden" name="action" value="reopen_month">
                        <input type="hidden" name="closing_month" value="<?php echo h($closingMonth); ?>">
                        <input type="hidden" name="store_id" value="<?php echo (int)$storeId; ?>">
                        <div class="input-group"><input type="text" name="notes" class="form-control" placeholder="Reopen reason"><button class="btn btn-outline-danger"><i class="bi bi-unlock me-1"></i>Reopen</button></div>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<div class="row g-4 mb-4 no-print">
    <div class="col-xl-6"><div class="card panel-card h-100"><div class="card-header"><h5 class="mb-0">Store Summary</h5></div><div class="card-body p-0"><table class="table table-modern mb-0"><thead><tr><th>Store</th><th class="text-end">Opening</th><th class="text-end">In</th><th class="text-end">Out</th><th class="text-end">Closing</th></tr></thead><tbody>
    <?php if (!$storeTotals): ?><tr><td colspan="5" class="text-center text-muted py-4">No store totals.</td></tr><?php else: foreach ($storeTotals as $name => $t): ?><tr><td><strong><?php echo h($name); ?></strong></td><td class="text-end"><?php echo money_fmt($t['opening']); ?></td><td class="text-end text-success"><?php echo money_fmt($t['in']); ?></td><td class="text-end text-danger"><?php echo money_fmt($t['out']); ?></td><td class="text-end fw-bold"><?php echo money_fmt($t['closing']); ?></td></tr><?php endforeach; endif; ?>
    </tbody></table></div></div></div>

    <div class="col-xl-6"><div class="card panel-card h-100"><div class="card-header"><h5 class="mb-0">Category Summary</h5></div><div class="card-body p-0"><table class="table table-modern mb-0"><thead><tr><th>Category</th><th class="text-end">Opening</th><th class="text-end">In</th><th class="text-end">Out</th><th class="text-end">Closing</th></tr></thead><tbody>
    <?php if (!$categoryTotals): ?><tr><td colspan="5" class="text-center text-muted py-4">No category totals.</td></tr><?php else: foreach ($categoryTotals as $name => $t): ?><tr><td><strong><?php echo h($name); ?></strong></td><td class="text-end"><?php echo money_fmt($t['opening']); ?></td><td class="text-end text-success"><?php echo money_fmt($t['in']); ?></td><td class="text-end text-danger"><?php echo money_fmt($t['out']); ?></td><td class="text-end fw-bold"><?php echo money_fmt($t['closing']); ?></td></tr><?php endforeach; endif; ?>
    </tbody></table></div></div></div>
</div>

<div class="card panel-card">
    <div class="card-header d-flex justify-content-between align-items-center"><h5 class="mb-0">Month-End Item Detail</h5><span class="text-muted small">Showing up to 3,000 rows</span></div>
    <div class="card-body p-0"><div class="table-responsive"><table class="table table-modern align-middle mb-0 closing-table">
        <thead><tr><th>Store</th><th>Category</th><th>Item</th><th class="text-end">Opening Qty</th><th class="text-end">In Qty</th><th class="text-end">Out Qty</th><th class="text-end">Closing Qty</th><th class="text-end">GRN Val</th><th class="text-end">Sales Cost</th><th class="text-end">Wastage</th><th class="text-end">Closing Val</th></tr></thead>
        <tbody>
        <?php if (!$rows): ?><tr><td colspan="11" class="text-center text-muted py-4">No month-end movement rows found.</td></tr><?php else: foreach ($rows as $row): $negative = (float)$row['closing_qty'] < 0; ?>
            <tr class="<?php echo $negative ? 'table-danger' : ''; ?>">
                <td><?php echo h($row['location_name']); ?></td>
                <td><?php echo h($row['category_name'] ?: 'Uncategorised'); ?></td>
                <td><strong><?php echo h($row['item_name']); ?></strong><div class="small text-muted"><?php echo h($row['item_code'] ?: ''); ?> <?php echo h($row['unit_code'] ?: ''); ?></div></td>
                <td class="text-end"><?php echo money_fmt($row['opening_qty']); ?></td>
                <td class="text-end text-success"><?php echo money_fmt($row['in_qty']); ?></td>
                <td class="text-end text-danger"><?php echo money_fmt($row['out_qty']); ?></td>
                <td class="text-end fw-bold"><?php echo money_fmt($row['closing_qty']); ?></td>
                <td class="text-end"><?php echo money_fmt($row['grn_value']); ?></td>
                <td class="text-end"><?php echo money_fmt($row['sale_value']); ?></td>
                <td class="text-end"><?php echo money_fmt($row['wastage_value']); ?></td>
                <td class="text-end fw-bold"><?php echo money_fmt($row['closing_value']); ?></td>
            </tr>
        <?php endforeach; endif; ?>
        </tbody>
        <tfoot><tr><th colspan="3" class="text-end">Totals</th><th class="text-end"><?php echo money_fmt($summary['opening_qty']); ?></th><th class="text-end"><?php echo money_fmt($summary['in_qty']); ?></th><th class="text-end"><?php echo money_fmt($summary['out_qty']); ?></th><th class="text-end"><?php echo money_fmt($summary['closing_qty']); ?></th><th class="text-end"><?php echo money_fmt($summary['in_value']); ?></th><th class="text-end"><?php echo money_fmt($summary['sales_value']); ?></th><th class="text-end"><?php echo money_fmt($summary['wastage_value']); ?></th><th class="text-end"><?php echo money_fmt($summary['closing_value']); ?></th></tr></tfoot>
    </table></div></div>
</div>

<style>
.small-value{font-size:1rem!important;letter-spacing:0!important}
.print-title{display:none}
.closing-table tfoot th{background:#0f172a!important;color:#fff!important}
@media print{
    .no-print,.sidebar,.enterprise-sidebar,.app-sidebar,.topbar,.navbar,.header,.footer{display:none!important}
    .print-title{display:block;margin-bottom:16px}
    .panel-card,.card{box-shadow:none!important;border:1px solid #ddd!important}
    body{background:#fff!important}
    .table{font-size:9.5px}
    .metric-card{box-shadow:none!important;border:1px solid #ddd!important}
}
</style>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
