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

$pageTitle = 'Inventory Shrinkage Dashboard';

if (file_exists(__DIR__ . '/../../includes/permission_check.php')) {
    require_once __DIR__ . '/../../includes/permission_check.php';
    if (function_exists('require_permission')) {
        require_permission($pdo, 'reports', 'view');
    }
}

if (!function_exists('h')) {
    function h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('money_fmt')) {
    function money_fmt($v): string { return number_format((float)$v, 2); }
}
if (!function_exists('qty_fmt')) {
    function qty_fmt($v): string { return number_format((float)$v, 4); }
}
if (!function_exists('isd_table_exists')) {
    function isd_table_exists(PDO $pdo, string $table): bool {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=:t");
        $stmt->execute([':t' => $table]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('isd_col_exists')) {
    function isd_col_exists(PDO $pdo, string $table, string $column): bool {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=:t AND column_name=:c");
        $stmt->execute([':t' => $table, ':c' => $column]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('isd_user_name_expr')) {
    function isd_user_name_expr(PDO $pdo, string $alias = 'u'): string {
        if (!isd_table_exists($pdo, 'users')) return "NULL";
        if (isd_col_exists($pdo, 'users', 'firstname') && isd_col_exists($pdo, 'users', 'lastname')) return "CONCAT({$alias}.firstname, ' ', {$alias}.lastname)";
        if (isd_col_exists($pdo, 'users', 'name')) return "{$alias}.name";
        if (isd_col_exists($pdo, 'users', 'full_name')) return "{$alias}.full_name";
        if (isd_col_exists($pdo, 'users', 'username')) return "{$alias}.username";
        if (isd_col_exists($pdo, 'users', 'email')) return "{$alias}.email";
        return "CONCAT('User #', {$alias}.id)";
    }
}

$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_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 stock_adjustment_headers (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        adjustment_no VARCHAR(60) NOT NULL,
        store_id INT UNSIGNED NOT NULL,
        item_id INT UNSIGNED NULL,
        adjustment_date DATE NOT NULL,
        adjustment_type ENUM('ADJUSTMENT_IN','ADJUSTMENT_OUT','WASTAGE') NOT NULL,
        reason VARCHAR(255) NOT NULL,
        notes TEXT NULL,
        total_qty 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,
        status ENUM('pending','approved','posted','rejected','void') NOT NULL DEFAULT 'pending',
        approved_by INT UNSIGNED NULL,
        approved_at DATETIME NULL,
        rejected_by INT UNSIGNED NULL,
        rejected_at DATETIME NULL,
        rejected_reason TEXT NULL,
        created_by INT UNSIGNED NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_adjustment_no (adjustment_no),
        INDEX idx_adjustment_store (store_id),
        INDEX idx_adjustment_item (item_id),
        INDEX idx_adjustment_date (adjustment_date),
        INDEX idx_adjustment_status (status)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Throwable $e) {
    $errors[] = 'Could not prepare shrinkage dashboard tables: ' . $e->getMessage();
}

$dateFrom = trim((string)($_GET['date_from'] ?? date('Y-m-01')));
$dateTo = trim((string)($_GET['date_to'] ?? date('Y-m-d')));
$storeId = (int)($_GET['store_id'] ?? 0);
$itemType = trim((string)($_GET['item_type'] ?? ''));
$search = trim((string)($_GET['q'] ?? ''));

if (strtotime($dateFrom) === false) $dateFrom = date('Y-m-01');
if (strtotime($dateTo) === false) $dateTo = date('Y-m-d');
if (strtotime($dateFrom) > strtotime($dateTo)) {
    $tmp = $dateFrom; $dateFrom = $dateTo; $dateTo = $tmp;
}

$stores = [];
$summary = [
    'shrink_qty' => 0,
    'shrink_value' => 0,
    'wastage_qty' => 0,
    'wastage_value' => 0,
    'adjust_out_qty' => 0,
    'adjust_out_value' => 0,
    'sales_qty' => 0,
    'sales_cost' => 0,
    'shrinkage_pct_cost' => 0,
    'pending_approvals' => 0,
    'posted_adjustments' => 0,
];
$byStore = [];
$byItem = [];
$recent = [];
$pending = [];
$approvals = [];
$trend = [];

try {
    $stores = $pdo->query("SELECT id, location_name FROM store_locations WHERE is_active=1 ORDER BY location_name ASC")->fetchAll(PDO::FETCH_ASSOC);

    $where = "DATE(sm.movement_date) BETWEEN :date_from AND :date_to";
    $params = [':date_from' => $dateFrom, ':date_to' => $dateTo];

    if ($storeId > 0) {
        $where .= " AND sm.store_id=:store_id";
        $params[':store_id'] = $storeId;
    }
    if ($itemType !== '') {
        $where .= " AND ii.item_type=:item_type";
        $params[':item_type'] = $itemType;
    }
    if ($search !== '') {
        $where .= " AND (ii.item_name LIKE :q OR ii.item_code LIKE :q OR sl.location_name LIKE :q OR sm.notes LIKE :q)";
        $params[':q'] = '%' . $search . '%';
    }

    $stmt = $pdo->prepare("
        SELECT
            SUM(CASE WHEN sm.movement_type IN ('ADJUSTMENT_OUT','WASTAGE') THEN sm.qty_out ELSE 0 END) AS shrink_qty,
            SUM(CASE WHEN sm.movement_type IN ('ADJUSTMENT_OUT','WASTAGE') THEN sm.total_cost ELSE 0 END) AS shrink_value,
            SUM(CASE WHEN sm.movement_type='WASTAGE' THEN sm.qty_out ELSE 0 END) AS wastage_qty,
            SUM(CASE WHEN sm.movement_type='WASTAGE' THEN sm.total_cost ELSE 0 END) AS wastage_value,
            SUM(CASE WHEN sm.movement_type='ADJUSTMENT_OUT' THEN sm.qty_out ELSE 0 END) AS adjust_out_qty,
            SUM(CASE WHEN sm.movement_type='ADJUSTMENT_OUT' THEN sm.total_cost ELSE 0 END) AS adjust_out_value,
            SUM(CASE WHEN sm.movement_type='SALE' THEN sm.qty_out ELSE 0 END) AS sales_qty,
            SUM(CASE WHEN sm.movement_type='SALE' THEN sm.total_cost ELSE 0 END) AS sales_cost
        FROM stock_movements sm
        LEFT JOIN inventory_items ii ON ii.id=sm.item_id
        LEFT JOIN store_locations sl ON sl.id=sm.store_id
        WHERE {$where}
    ");
    $stmt->execute($params);
    $row = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

    foreach (['shrink_qty','shrink_value','wastage_qty','wastage_value','adjust_out_qty','adjust_out_value','sales_qty','sales_cost'] as $k) {
        $summary[$k] = (float)($row[$k] ?? 0);
    }

    $baseCost = $summary['sales_cost'] + $summary['shrink_value'];
    $summary['shrinkage_pct_cost'] = $baseCost > 0 ? ($summary['shrink_value'] / $baseCost) * 100 : 0;

    $adjWhere = "DATE(ah.created_at) BETWEEN :date_from AND :date_to";
    $adjParams = [':date_from' => $dateFrom, ':date_to' => $dateTo];
    if ($storeId > 0) {
        $adjWhere .= " AND ah.store_id=:store_id";
        $adjParams[':store_id'] = $storeId;
    }
    if ($itemType !== '') {
        $adjWhere .= " AND ii.item_type=:item_type";
        $adjParams[':item_type'] = $itemType;
    }
    if ($search !== '') {
        $adjWhere .= " AND (ah.reason LIKE :q OR ah.adjustment_no LIKE :q OR ii.item_name LIKE :q OR sl.location_name LIKE :q)";
        $adjParams[':q'] = '%' . $search . '%';
    }

    $stmt = $pdo->prepare("
        SELECT
            SUM(CASE WHEN ah.status='pending' THEN 1 ELSE 0 END) AS pending_count,
            SUM(CASE WHEN ah.status='posted' THEN 1 ELSE 0 END) AS posted_count
        FROM stock_adjustment_headers ah
        LEFT JOIN inventory_items ii ON ii.id=ah.item_id
        LEFT JOIN store_locations sl ON sl.id=ah.store_id
        WHERE {$adjWhere}
    ");
    $stmt->execute($adjParams);
    $row = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
    $summary['pending_approvals'] = (int)($row['pending_count'] ?? 0);
    $summary['posted_adjustments'] = (int)($row['posted_count'] ?? 0);

    $stmt = $pdo->prepare("
        SELECT
            sl.id AS store_id,
            sl.location_name,
            SUM(CASE WHEN sm.movement_type IN ('ADJUSTMENT_OUT','WASTAGE') THEN sm.qty_out ELSE 0 END) AS shrink_qty,
            SUM(CASE WHEN sm.movement_type IN ('ADJUSTMENT_OUT','WASTAGE') THEN sm.total_cost ELSE 0 END) AS shrink_value,
            SUM(CASE WHEN sm.movement_type='SALE' THEN sm.total_cost ELSE 0 END) AS sales_cost
        FROM stock_movements sm
        LEFT JOIN inventory_items ii ON ii.id=sm.item_id
        LEFT JOIN store_locations sl ON sl.id=sm.store_id
        WHERE {$where}
        GROUP BY sl.id, sl.location_name
        HAVING shrink_qty > 0 OR shrink_value > 0
        ORDER BY shrink_value DESC
        LIMIT 20
    ");
    $stmt->execute($params);
    $byStore = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt = $pdo->prepare("
        SELECT
            ii.id AS item_id,
            ii.item_code,
            ii.item_name,
            ii.item_type,
            u.unit_code,
            sl.location_name,
            SUM(CASE WHEN sm.movement_type IN ('ADJUSTMENT_OUT','WASTAGE') THEN sm.qty_out ELSE 0 END) AS shrink_qty,
            SUM(CASE WHEN sm.movement_type IN ('ADJUSTMENT_OUT','WASTAGE') THEN sm.total_cost ELSE 0 END) AS shrink_value,
            SUM(CASE WHEN sm.movement_type='WASTAGE' THEN sm.qty_out ELSE 0 END) AS wastage_qty,
            SUM(CASE WHEN sm.movement_type='ADJUSTMENT_OUT' THEN sm.qty_out ELSE 0 END) AS adjust_out_qty,
            COUNT(CASE WHEN sm.movement_type IN ('ADJUSTMENT_OUT','WASTAGE') THEN 1 END) AS incident_count
        FROM stock_movements sm
        LEFT JOIN inventory_items ii ON ii.id=sm.item_id
        LEFT JOIN inventory_units u ON u.id=ii.unit_id
        LEFT JOIN store_locations sl ON sl.id=sm.store_id
        WHERE {$where}
        GROUP BY ii.id, ii.item_code, ii.item_name, ii.item_type, u.unit_code, sl.location_name
        HAVING shrink_qty > 0 OR shrink_value > 0
        ORDER BY shrink_value DESC, incident_count DESC
        LIMIT 30
    ");
    $stmt->execute($params);
    $byItem = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt = $pdo->prepare("
        SELECT
            sm.*,
            ii.item_code,
            ii.item_name,
            ii.item_type,
            u.unit_code,
            sl.location_name,
            ah.adjustment_no,
            ah.reason,
            ah.status AS adjustment_status,
            ah.approved_at
        FROM stock_movements sm
        LEFT JOIN inventory_items ii ON ii.id=sm.item_id
        LEFT JOIN inventory_units u ON u.id=ii.unit_id
        LEFT JOIN store_locations sl ON sl.id=sm.store_id
        LEFT JOIN stock_adjustment_headers ah
            ON ah.id=sm.reference_id
           AND sm.reference_type='STOCK_ADJUSTMENT'
        WHERE {$where}
          AND sm.movement_type IN ('ADJUSTMENT_OUT','WASTAGE')
        ORDER BY sm.movement_date DESC, sm.id DESC
        LIMIT 100
    ");
    $stmt->execute($params);
    $recent = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $createdName = isd_user_name_expr($pdo, 'cu');
    $pendingUserJoins = isd_table_exists($pdo, 'users') ? "LEFT JOIN users cu ON cu.id=ah.created_by" : "";

    $stmt = $pdo->prepare("
        SELECT
            ah.*,
            ii.item_code,
            ii.item_name,
            u.unit_code,
            sl.location_name,
            {$createdName} AS created_by_name
        FROM stock_adjustment_headers ah
        LEFT JOIN inventory_items ii ON ii.id=ah.item_id
        LEFT JOIN inventory_units u ON u.id=ii.unit_id
        LEFT JOIN store_locations sl ON sl.id=ah.store_id
        {$pendingUserJoins}
        WHERE ah.status='pending'
        " . ($storeId > 0 ? " AND ah.store_id=:store_id " : "") . "
        ORDER BY ah.created_at DESC
        LIMIT 30
    ");
    $pendingParams = [];
    if ($storeId > 0) $pendingParams[':store_id'] = $storeId;
    $stmt->execute($pendingParams);
    $pending = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (isd_table_exists($pdo, 'manager_approval_log')) {
        $managerName = isd_user_name_expr($pdo, 'mu');
        $requestedName = isd_user_name_expr($pdo, 'ru');

        $stmt = $pdo->prepare("
            SELECT
                mal.*,
                {$managerName} AS manager_name,
                {$requestedName} AS requested_by_name
            FROM manager_approval_log mal
            " . (isd_table_exists($pdo, 'users') ? "
                LEFT JOIN users mu ON mu.id=mal.manager_user_id
                LEFT JOIN users ru ON ru.id=mal.requested_by
            " : "") . "
            WHERE DATE(mal.created_at) BETWEEN :date_from AND :date_to
              AND mal.reference_type='stock_adjustment'
            ORDER BY mal.created_at DESC
            LIMIT 50
        ");
        $stmt->execute([':date_from' => $dateFrom, ':date_to' => $dateTo]);
        $approvals = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    $stmt = $pdo->prepare("
        SELECT
            DATE(sm.movement_date) AS movement_day,
            SUM(CASE WHEN sm.movement_type IN ('ADJUSTMENT_OUT','WASTAGE') THEN sm.total_cost ELSE 0 END) AS shrink_value,
            SUM(CASE WHEN sm.movement_type='SALE' THEN sm.total_cost ELSE 0 END) AS sales_cost
        FROM stock_movements sm
        LEFT JOIN inventory_items ii ON ii.id=sm.item_id
        LEFT JOIN store_locations sl ON sl.id=sm.store_id
        WHERE {$where}
        GROUP BY DATE(sm.movement_date)
        ORDER BY movement_day ASC
    ");
    $stmt->execute($params);
    $trend = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (Throwable $e) {
    $errors[] = 'Could not load shrinkage dashboard data: ' . $e->getMessage();
}

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-exclamation-triangle"></i> Inventory Risk</div>
            <div class="hero-title mt-2">Inventory Shrinkage Dashboard</div>
            <div class="hero-subtitle mt-2">
                Track wastage, write-offs, adjustment losses, high-risk items and pending approvals.
            </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="stock_audit_trail_report.php" class="btn btn-outline-light">
                <i class="bi bi-shield-check me-2"></i>Audit Trail
            </a>
        </div>
    </div>
</div>

<?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="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">From</label>
                <input type="date" name="date_from" class="form-control" value="<?php echo h($dateFrom); ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">To</label>
                <input type="date" name="date_to" class="form-control" value="<?php echo h($dateTo); ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label">Store</label>
                <select name="store_id" class="form-select">
                    <option value="0">All stores</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">Item Type</label>
                <select name="item_type" class="form-select">
                    <option value="">All</option>
                    <?php foreach (['stock','food','bar','curio','consumable','service','recipe','other'] as $type): ?>
                        <option value="<?php echo h($type); ?>" <?php echo $itemType === $type ? 'selected' : ''; ?>>
                            <?php echo h(ucwords($type)); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Search</label>
                <input type="text" name="q" class="form-control" value="<?php echo h($search); ?>" placeholder="Item / store / notes">
            </div>
            <div class="col-md-1 d-grid">
                <button class="btn btn-primary"><i class="bi bi-funnel"></i></button>
            </div>
        </form>
    </div>
</div>

<div class="row g-4 mb-4">
    <div class="col-md-6 col-xl-3">
        <div class="metric-card risk-card">
            <div class="metric-icon bg-danger-subtle text-danger"><i class="bi bi-cash-stack"></i></div>
            <div><div class="metric-label">Shrinkage Value</div><div class="metric-value small-value"><?php echo money_fmt($summary['shrink_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-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-primary-subtle text-primary"><i class="bi bi-percent"></i></div>
            <div><div class="metric-label">Shrinkage % Cost</div><div class="metric-value small-value"><?php echo number_format($summary['shrinkage_pct_cost'], 2); ?>%</div></div>
        </div>
    </div>
    <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-hourglass-split"></i></div>
            <div><div class="metric-label">Pending Approvals</div><div class="metric-value"><?php echo (int)$summary['pending_approvals']; ?></div></div>
        </div>
    </div>
</div>

<div class="row g-4 mb-4">
    <div class="col-xl-8">
        <div class="card panel-card h-100">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">High-Risk Items</h5>
                <span class="small text-muted">By shrinkage value</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive dash-table">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                        <tr>
                            <th>Item</th>
                            <th>Store</th>
                            <th>Type</th>
                            <th class="text-end">Shrink Qty</th>
                            <th class="text-end">Wastage</th>
                            <th class="text-end">Write-off</th>
                            <th class="text-end">Value</th>
                            <th class="text-end">Incidents</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$byItem): ?>
                            <tr><td colspan="8" class="text-center text-muted py-4">No shrinkage found for this period.</td></tr>
                        <?php else: foreach ($byItem as $row): ?>
                            <tr>
                                <td>
                                    <strong><?php echo h($row['item_name'] ?: 'Item'); ?></strong>
                                    <div class="small text-muted"><?php echo h($row['item_code'] ?? ''); ?></div>
                                </td>
                                <td><?php echo h($row['location_name'] ?: 'Store'); ?></td>
                                <td><span class="badge text-bg-light border"><?php echo h(ucwords($row['item_type'] ?: 'stock')); ?></span></td>
                                <td class="text-end"><?php echo qty_fmt($row['shrink_qty']); ?> <?php echo h($row['unit_code'] ?? ''); ?></td>
                                <td class="text-end"><?php echo qty_fmt($row['wastage_qty']); ?></td>
                                <td class="text-end"><?php echo qty_fmt($row['adjust_out_qty']); ?></td>
                                <td class="text-end fw-bold text-danger"><?php echo money_fmt($row['shrink_value']); ?></td>
                                <td class="text-end"><?php echo (int)$row['incident_count']; ?></td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-4">
        <div class="card panel-card h-100">
            <div class="card-header">
                <h5 class="mb-0">Shrinkage by Store</h5>
            </div>
            <div class="card-body">
                <?php if (!$byStore): ?>
                    <div class="text-muted">No shrinkage by store for this period.</div>
                <?php else: ?>
                    <?php
                    $maxStoreValue = 0;
                    foreach ($byStore as $s) $maxStoreValue = max($maxStoreValue, (float)$s['shrink_value']);
                    ?>
                    <?php foreach ($byStore as $s): ?>
                        <?php
                        $value = (float)$s['shrink_value'];
                        $pct = $maxStoreValue > 0 ? ($value / $maxStoreValue) * 100 : 0;
                        $base = (float)$s['sales_cost'] + $value;
                        $storeShrinkPct = $base > 0 ? ($value / $base) * 100 : 0;
                        ?>
                        <div class="store-risk-row">
                            <div class="d-flex justify-content-between">
                                <strong><?php echo h($s['location_name'] ?: 'Store'); ?></strong>
                                <span class="text-danger fw-bold"><?php echo money_fmt($value); ?></span>
                            </div>
                            <div class="risk-bar"><span style="width:<?php echo (float)$pct; ?>%"></span></div>
                            <div class="small text-muted">
                                Qty: <?php echo qty_fmt($s['shrink_qty']); ?> • Shrinkage: <?php echo number_format($storeShrinkPct, 2); ?>%
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<div class="row g-4 mb-4">
    <div class="col-xl-6">
        <div class="card panel-card h-100">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Pending Adjustment Approvals</h5>
                <a href="stock_adjustment_approvals.php" class="btn btn-sm btn-outline-primary no-print">Open Approvals</a>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive dash-table-sm">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                        <tr>
                            <th>No</th>
                            <th>Item</th>
                            <th>Store</th>
                            <th class="text-end">Qty</th>
                            <th class="text-end">Value</th>
                            <th>Requested By</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$pending): ?>
                            <tr><td colspan="6" class="text-center text-muted py-4">No pending stock adjustment approvals.</td></tr>
                        <?php else: foreach ($pending as $p): ?>
                            <tr class="table-warning">
                                <td><a href="stock_adjustment_approvals.php?adjustment_id=<?php echo (int)$p['id']; ?>"><strong><?php echo h($p['adjustment_no']); ?></strong></a></td>
                                <td><?php echo h($p['item_name'] ?: 'Item'); ?></td>
                                <td><?php echo h($p['location_name'] ?: 'Store'); ?></td>
                                <td class="text-end"><?php echo qty_fmt($p['total_qty']); ?> <?php echo h($p['unit_code'] ?? ''); ?></td>
                                <td class="text-end"><?php echo money_fmt($p['total_cost']); ?></td>
                                <td><?php echo h($p['created_by_name'] ?: 'User'); ?></td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-6">
        <div class="card panel-card h-100">
            <div class="card-header">
                <h5 class="mb-0">Recent Manager Approvals</h5>
            </div>
            <div class="card-body p-0">
                <div class="approval-list">
                    <?php if (!$approvals): ?>
                        <div class="p-3 text-muted">No stock adjustment approvals in this period.</div>
                    <?php else: foreach ($approvals as $a): ?>
                        <div class="approval-item">
                            <div class="fw-bold"><?php echo h($a['action_label'] ?: 'Stock adjustment approval'); ?></div>
                            <div class="small text-muted"><?php echo h($a['created_at']); ?></div>
                            <div class="small">
                                Manager: <strong><?php echo h($a['manager_name'] ?: ('User #' . $a['manager_user_id'])); ?></strong>
                                <?php if (!empty($a['requested_by_name'])): ?>
                                    • Requested by: <?php echo h($a['requested_by_name']); ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card panel-card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Recent Shrinkage Incidents</h5>
        <span class="small text-muted">Adjustment out + wastage movements</span>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive dash-table">
            <table class="table table-modern align-middle mb-0">
                <thead>
                <tr>
                    <th>Date</th>
                    <th>Item</th>
                    <th>Store</th>
                    <th>Type</th>
                    <th class="text-end">Qty</th>
                    <th class="text-end">Value</th>
                    <th>Reason / Notes</th>
                    <th>Reference</th>
                </tr>
                </thead>
                <tbody>
                <?php if (!$recent): ?>
                    <tr><td colspan="8" class="text-center text-muted py-4">No shrinkage incidents found.</td></tr>
                <?php else: foreach ($recent as $r): ?>
                    <tr>
                        <td><?php echo h($r['movement_date']); ?></td>
                        <td><strong><?php echo h($r['item_name'] ?: 'Item'); ?></strong><div class="small text-muted"><?php echo h($r['item_code'] ?? ''); ?></div></td>
                        <td><?php echo h($r['location_name'] ?: 'Store'); ?></td>
                        <td>
                            <span class="badge <?php echo $r['movement_type'] === 'WASTAGE' ? 'text-bg-danger' : 'text-bg-warning'; ?>">
                                <?php echo h(str_replace('_',' ', $r['movement_type'])); ?>
                            </span>
                        </td>
                        <td class="text-end"><?php echo qty_fmt($r['qty_out']); ?> <?php echo h($r['unit_code'] ?? ''); ?></td>
                        <td class="text-end fw-bold text-danger"><?php echo money_fmt($r['total_cost']); ?></td>
                        <td class="small">
                            <?php echo h($r['reason'] ?: $r['notes']); ?>
                        </td>
                        <td>
                            <?php if (!empty($r['adjustment_no'])): ?>
                                <a href="stock_adjustments.php?adjustment_id=<?php echo (int)$r['reference_id']; ?>"><?php echo h($r['adjustment_no']); ?></a>
                                <div class="small text-muted"><?php echo h($r['adjustment_status']); ?></div>
                            <?php else: ?>
                                <?php echo h($r['reference_type'] ?: '—'); ?>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<style>
.small-value{font-size:1rem!important;letter-spacing:0!important}
.risk-card{border:1px solid rgba(220,38,38,.25)}
.dash-table{max-height:620px;overflow:auto}
.dash-table-sm{max-height:360px;overflow:auto}
.store-risk-row{padding:12px 0;border-bottom:1px solid rgba(15,23,42,.08)}
.store-risk-row:last-child{border-bottom:0}
.risk-bar{height:9px;border-radius:999px;background:#fee2e2;overflow:hidden;margin:8px 0}
.risk-bar span{display:block;height:100%;background:#dc2626;border-radius:999px}
.approval-list{max-height:360px;overflow:auto}
.approval-item{padding:12px 14px;border-bottom:1px solid rgba(15,23,42,.08)}
.approval-item:last-child{border-bottom:0}
@media print{
    .no-print,.sidebar,.enterprise-sidebar,.app-sidebar,.topbar,.navbar,.header,.footer{display:none!important}
    body{background:#fff!important}
    .panel-card,.card,.metric-card{box-shadow:none!important}
    .dash-table,.dash-table-sm,.approval-list{max-height:none!important;overflow:visible!important}
}
</style>

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