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

$pageTitle = 'Stock Audit Trail';

if (file_exists(__DIR__ . '/../../includes/permission_check.php')) {
    require_once __DIR__ . '/../../includes/permission_check.php';
    if (function_exists('require_permission')) {
        require_permission($pdo, 'audit_log', '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('sat_table_exists')) {
    function sat_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('sat_col_exists')) {
    function sat_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('sat_user_name_expr')) {
    function sat_user_name_expr(PDO $pdo, string $alias = 'u'): string {
        if (!sat_table_exists($pdo, 'users')) return "NULL";
        if (sat_col_exists($pdo, 'users', 'firstname') && sat_col_exists($pdo, 'users', 'lastname')) return "CONCAT({$alias}.firstname, ' ', {$alias}.lastname)";
        if (sat_col_exists($pdo, 'users', 'name')) return "{$alias}.name";
        if (sat_col_exists($pdo, 'users', 'full_name')) return "{$alias}.full_name";
        if (sat_col_exists($pdo, 'users', 'username')) return "{$alias}.username";
        if (sat_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 stock audit 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);
$itemId = (int)($_GET['item_id'] ?? 0);
$movementType = trim((string)($_GET['movement_type'] ?? ''));
$referenceType = trim((string)($_GET['reference_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 = [];
$items = [];
$movements = [];
$adjustments = [];
$approvals = [];

$summary = [
    'qty_in' => 0,
    'qty_out' => 0,
    'net_qty' => 0,
    'value_in' => 0,
    'value_out' => 0,
    'adjustments_pending' => 0,
    'adjustments_posted' => 0,
    'adjustments_rejected' => 0,
    'approval_count' => 0,
];

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

    $items = $pdo->query("
        SELECT ii.id, ii.item_code, ii.item_name, u.unit_code
        FROM inventory_items ii
        LEFT JOIN inventory_units u ON u.id=ii.unit_id
        WHERE ii.is_active=1
        ORDER BY ii.item_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 ($itemId > 0) {
        $where .= " AND sm.item_id=:item_id";
        $params[':item_id'] = $itemId;
    }

    if ($movementType !== '') {
        $where .= " AND sm.movement_type=:movement_type";
        $params[':movement_type'] = $movementType;
    }

    if ($referenceType !== '') {
        $where .= " AND sm.reference_type=:reference_type";
        $params[':reference_type'] = $referenceType;
    }

    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 OR sm.reference_type LIKE :q)";
        $params[':q'] = '%' . $search . '%';
    }

    $stmt = $pdo->prepare("
        SELECT
            sm.*,
            ii.item_name,
            ii.item_code,
            u.unit_code,
            sl.location_name,
            ah.adjustment_no,
            ah.reason AS adjustment_reason,
            ah.status AS adjustment_status,
            ah.approved_by,
            ah.approved_at,
            ah.created_by,
            ah.rejected_by,
            ah.rejected_at,
            ah.rejected_reason
        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}
        ORDER BY sm.movement_date DESC, sm.id DESC
        LIMIT 1000
    ");
    $stmt->execute($params);
    $movements = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($movements as $m) {
        $qtyIn = (float)$m['qty_in'];
        $qtyOut = (float)$m['qty_out'];
        $cost = (float)$m['total_cost'];

        $summary['qty_in'] += $qtyIn;
        $summary['qty_out'] += $qtyOut;

        if ($qtyIn > 0) $summary['value_in'] += $cost;
        if ($qtyOut > 0) $summary['value_out'] += $cost;
    }
    $summary['net_qty'] = $summary['qty_in'] - $summary['qty_out'];

    $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 ($itemId > 0) {
        $adjWhere .= " AND ah.item_id=:item_id";
        $adjParams[':item_id'] = $itemId;
    }
    if ($search !== '') {
        $adjWhere .= " AND (ah.adjustment_no LIKE :q OR ah.reason LIKE :q OR ah.notes LIKE :q OR ii.item_name LIKE :q OR ii.item_code LIKE :q OR sl.location_name LIKE :q)";
        $adjParams[':q'] = '%' . $search . '%';
    }

    $createdByName = sat_user_name_expr($pdo, 'cu');
    $approvedByName = sat_user_name_expr($pdo, 'au');
    $rejectedByName = sat_user_name_expr($pdo, 'ru');

    $userJoins = sat_table_exists($pdo, 'users') ? "
        LEFT JOIN users cu ON cu.id=ah.created_by
        LEFT JOIN users au ON au.id=ah.approved_by
        LEFT JOIN users ru ON ru.id=ah.rejected_by
    " : "";

    $stmt = $pdo->prepare("
        SELECT
            ah.*,
            sl.location_name,
            ii.item_name,
            ii.item_code,
            u.unit_code,
            {$createdByName} AS created_by_name,
            {$approvedByName} AS approved_by_name,
            {$rejectedByName} AS rejected_by_name
        FROM stock_adjustment_headers ah
        LEFT JOIN store_locations sl ON sl.id=ah.store_id
        LEFT JOIN inventory_items ii ON ii.id=ah.item_id
        LEFT JOIN inventory_units u ON u.id=ii.unit_id
        {$userJoins}
        WHERE {$adjWhere}
        ORDER BY ah.created_at DESC, ah.id DESC
        LIMIT 500
    ");
    $stmt->execute($adjParams);
    $adjustments = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($adjustments as $a) {
        if ($a['status'] === 'pending') $summary['adjustments_pending']++;
        if ($a['status'] === 'posted') $summary['adjustments_posted']++;
        if ($a['status'] === 'rejected') $summary['adjustments_rejected']++;
    }

    if (sat_table_exists($pdo, 'manager_approval_log')) {
        $approvalWhere = "DATE(mal.created_at) BETWEEN :date_from AND :date_to";
        $approvalParams = [
            ':date_from' => $dateFrom,
            ':date_to' => $dateTo,
        ];

        if ($search !== '') {
            $approvalWhere .= " AND (mal.permission_key LIKE :q OR mal.action_label LIKE :q OR mal.reference_type LIKE :q OR mal.notes LIKE :q)";
            $approvalParams[':q'] = '%' . $search . '%';
        }

        $managerName = sat_user_name_expr($pdo, 'mu');
        $requestedName = sat_user_name_expr($pdo, 'ru');

        $stmt = $pdo->prepare("
            SELECT
                mal.*,
                {$managerName} AS manager_name,
                {$requestedName} AS requested_by_name
            FROM manager_approval_log mal
            " . (sat_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 {$approvalWhere}
              AND (mal.reference_type IN ('stock_adjustment','pos_order') OR mal.permission_key IN ('stock_movements','pos_void'))
            ORDER BY mal.created_at DESC, mal.id DESC
            LIMIT 300
        ");
        $stmt->execute($approvalParams);
        $approvals = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $summary['approval_count'] = count($approvals);
    }

} catch (Throwable $e) {
    $errors[] = 'Could not load stock audit trail: ' . $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-shield-check"></i> Inventory Control</div>
            <div class="hero-title mt-2">Stock Audit Trail</div>
            <div class="hero-subtitle mt-2">
                Full trace of stock movements, adjustments, approvals, quantities, values and users.
            </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_movements.php" class="btn btn-outline-light">
                <i class="bi bi-arrow-left-right me-2"></i>Movements
            </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-2">
                <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</label>
                <select name="item_id" class="form-select">
                    <option value="0">All items</option>
                    <?php foreach ($items as $item): ?>
                        <option value="<?php echo (int)$item['id']; ?>" <?php echo $itemId === (int)$item['id'] ? 'selected' : ''; ?>>
                            <?php echo h($item['item_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Movement</label>
                <select name="movement_type" class="form-select">
                    <option value="">All</option>
                    <?php foreach (['OPENING','GRN','ISSUE','SALE','TRANSFER_IN','TRANSFER_OUT','ADJUSTMENT_IN','ADJUSTMENT_OUT','WASTAGE','RETURN'] as $mt): ?>
                        <option value="<?php echo h($mt); ?>" <?php echo $movementType === $mt ? 'selected' : ''; ?>>
                            <?php echo h(str_replace('_',' ', $mt)); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-1">
                <label class="form-label">Search</label>
                <input type="text" name="q" class="form-control" value="<?php echo h($search); ?>">
            </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">
            <div class="metric-icon bg-success-subtle text-success"><i class="bi bi-arrow-down-circle"></i></div>
            <div><div class="metric-label">Qty In</div><div class="metric-value small-value"><?php echo qty_fmt($summary['qty_in']); ?></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">Qty Out</div><div class="metric-value small-value"><?php echo qty_fmt($summary['qty_out']); ?></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-balance-scale"></i></div>
            <div><div class="metric-label">Net Qty</div><div class="metric-value small-value"><?php echo qty_fmt($summary['net_qty']); ?></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-shield-lock"></i></div>
            <div><div class="metric-label">Approvals</div><div class="metric-value"><?php echo (int)$summary['approval_count']; ?></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">Stock Movement Trail</h5>
                <span class="small text-muted">Latest 1000 movements</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive audit-table-wrap">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                        <tr>
                            <th>Date</th>
                            <th>Item</th>
                            <th>Store</th>
                            <th>Movement</th>
                            <th class="text-end">Qty In</th>
                            <th class="text-end">Qty Out</th>
                            <th class="text-end">Cost</th>
                            <th>Reference</th>
                            <th>Notes</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$movements): ?>
                            <tr><td colspan="9" class="text-center text-muted py-4">No stock movements found.</td></tr>
                        <?php else: foreach ($movements as $m): ?>
                            <tr>
                                <td><?php echo h($m['movement_date']); ?></td>
                                <td>
                                    <strong><?php echo h($m['item_name'] ?: 'Item'); ?></strong>
                                    <div class="small text-muted"><?php echo h($m['item_code'] ?? ''); ?></div>
                                </td>
                                <td><?php echo h($m['location_name'] ?: 'Store'); ?></td>
                                <td>
                                    <span class="badge <?php echo ((float)$m['qty_in'] > 0) ? 'text-bg-success' : 'text-bg-warning'; ?>">
                                        <?php echo h(str_replace('_',' ', $m['movement_type'])); ?>
                                    </span>
                                </td>
                                <td class="text-end"><?php echo qty_fmt($m['qty_in']); ?> <?php echo h($m['unit_code'] ?? ''); ?></td>
                                <td class="text-end"><?php echo qty_fmt($m['qty_out']); ?> <?php echo h($m['unit_code'] ?? ''); ?></td>
                                <td class="text-end"><?php echo money_fmt($m['total_cost']); ?></td>
                                <td>
                                    <?php echo h($m['reference_type'] ?: '—'); ?>
                                    <?php if (!empty($m['adjustment_no'])): ?>
                                        <div class="small"><a href="stock_adjustments.php?adjustment_id=<?php echo (int)$m['reference_id']; ?>"><?php echo h($m['adjustment_no']); ?></a></div>
                                    <?php elseif (!empty($m['reference_id'])): ?>
                                        <div class="small text-muted">#<?php echo (int)$m['reference_id']; ?></div>
                                    <?php endif; ?>
                                </td>
                                <td class="small"><?php echo h(mb_strimwidth((string)$m['notes'], 0, 80, '...')); ?></td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-4">
        <div class="card panel-card mb-4">
            <div class="card-header"><h5 class="mb-0">Adjustment Status</h5></div>
            <div class="card-body">
                <div class="status-row"><span>Pending</span><strong class="text-warning"><?php echo (int)$summary['adjustments_pending']; ?></strong></div>
                <div class="status-row"><span>Posted</span><strong class="text-success"><?php echo (int)$summary['adjustments_posted']; ?></strong></div>
                <div class="status-row"><span>Rejected</span><strong class="text-danger"><?php echo (int)$summary['adjustments_rejected']; ?></strong></div>
                <hr>
                <div class="status-row"><span>Value In</span><strong><?php echo money_fmt($summary['value_in']); ?></strong></div>
                <div class="status-row"><span>Value Out</span><strong><?php echo money_fmt($summary['value_out']); ?></strong></div>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header"><h5 class="mb-0">Manager Approval Logs</h5></div>
            <div class="card-body p-0">
                <div class="approval-list">
                    <?php if (!$approvals): ?>
                        <div class="p-3 text-muted">No manager approvals found.</div>
                    <?php else: foreach ($approvals as $a): ?>
                        <div class="approval-item">
                            <div class="fw-bold"><?php echo h($a['action_label'] ?: $a['permission_key']); ?></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>
                            </div>
                            <div class="small text-muted">
                                Reference: <?php echo h($a['reference_type'] ?: '—'); ?>
                                <?php echo !empty($a['reference_id']) ? '#' . (int)$a['reference_id'] : ''; ?>
                            </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">Adjustment Request Audit</h5>
        <span class="small text-muted">Latest 500 adjustment requests</span>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive audit-table-wrap">
            <table class="table table-modern align-middle mb-0">
                <thead>
                <tr>
                    <th>Created</th>
                    <th>No</th>
                    <th>Item</th>
                    <th>Store</th>
                    <th>Type</th>
                    <th class="text-end">Qty</th>
                    <th class="text-end">Value</th>
                    <th>Status</th>
                    <th>Requested By</th>
                    <th>Approved / Rejected By</th>
                    <th>Reason</th>
                </tr>
                </thead>
                <tbody>
                <?php if (!$adjustments): ?>
                    <tr><td colspan="11" class="text-center text-muted py-4">No adjustment requests found.</td></tr>
                <?php else: foreach ($adjustments as $a): ?>
                    <tr class="<?php echo $a['status'] === 'pending' ? 'table-warning' : ($a['status'] === 'rejected' ? 'table-danger' : ''); ?>">
                        <td><?php echo h($a['created_at']); ?></td>
                        <td><strong><?php echo h($a['adjustment_no']); ?></strong></td>
                        <td><?php echo h($a['item_name'] ?: 'Item'); ?><div class="small text-muted"><?php echo h($a['item_code'] ?? ''); ?></div></td>
                        <td><?php echo h($a['location_name'] ?: 'Store'); ?></td>
                        <td><?php echo h(str_replace('_',' ', $a['adjustment_type'])); ?></td>
                        <td class="text-end"><?php echo qty_fmt($a['total_qty']); ?> <?php echo h($a['unit_code'] ?? ''); ?></td>
                        <td class="text-end"><?php echo money_fmt($a['total_cost']); ?></td>
                        <td>
                            <span class="badge <?php echo $a['status'] === 'pending' ? 'text-bg-warning' : ($a['status'] === 'posted' ? 'text-bg-success' : 'text-bg-danger'); ?>">
                                <?php echo h(ucwords($a['status'])); ?>
                            </span>
                        </td>
                        <td><?php echo h($a['created_by_name'] ?: 'User'); ?></td>
                        <td>
                            <?php if ($a['status'] === 'posted'): ?>
                                <?php echo h($a['approved_by_name'] ?: 'Manager'); ?>
                                <div class="small text-muted"><?php echo h($a['approved_at']); ?></div>
                            <?php elseif ($a['status'] === 'rejected'): ?>
                                <?php echo h($a['rejected_by_name'] ?: 'User'); ?>
                                <div class="small text-muted"><?php echo h($a['rejected_at']); ?></div>
                            <?php else: ?>
                                <span class="text-muted">Pending</span>
                            <?php endif; ?>
                        </td>
                        <td class="small">
                            <?php echo h(mb_strimwidth((string)$a['reason'], 0, 70, '...')); ?>
                            <?php if (!empty($a['rejected_reason'])): ?>
                                <div class="text-danger">Rejected: <?php echo h(mb_strimwidth((string)$a['rejected_reason'], 0, 70, '...')); ?></div>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<style>
.small-value{font-size:1rem!important;letter-spacing:0!important}
.audit-table-wrap{max-height:640px;overflow:auto}
.status-row{display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid rgba(15,23,42,.08);padding:12px 0}
.status-row:last-child{border-bottom:0}
.approval-list{max-height:430px;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}
    .audit-table-wrap,.approval-list{max-height:none!important;overflow:visible!important}
}
</style>

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