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

$pageTitle = 'Stock Adjustment Approvals';

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

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('saa_flash')) {
    function saa_flash(string $type, string $message): void {
        $_SESSION['stock_adjustment_approval_flash'][] = ['type' => $type, 'message' => $message];
    }
}
if (!function_exists('saa_get_flash')) {
    function saa_get_flash(): array {
        $items = $_SESSION['stock_adjustment_approval_flash'] ?? [];
        unset($_SESSION['stock_adjustment_approval_flash']);
        return $items;
    }
}
if (!function_exists('saa_table_exists')) {
    function saa_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('saa_col_exists')) {
    function saa_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('saa_add_col')) {
    function saa_add_col(PDO $pdo, string $table, string $column, string $sql): void {
        if (!saa_col_exists($pdo, $table, $column)) {
            $pdo->exec($sql);
        }
    }
}
if (!function_exists('saa_stock_balance')) {
    function saa_stock_balance(PDO $pdo, int $itemId, int $storeId): float {
        $stmt = $pdo->prepare("
            SELECT COALESCE(SUM(qty_in - qty_out), 0)
            FROM stock_movements
            WHERE item_id = :item_id
              AND store_id = :store_id
        ");
        $stmt->execute([':item_id' => $itemId, ':store_id' => $storeId]);
        return (float)$stmt->fetchColumn();
    }
}
if (!function_exists('saa_user_name_expr')) {
    function saa_user_name_expr(PDO $pdo, string $alias = 'u'): string {
        if (!saa_table_exists($pdo, 'users')) return "NULL";
        if (saa_col_exists($pdo, 'users', 'firstname') && saa_col_exists($pdo, 'users', 'lastname')) return "CONCAT({$alias}.firstname, ' ', {$alias}.lastname)";
        if (saa_col_exists($pdo, 'users', 'name')) return "{$alias}.name";
        if (saa_col_exists($pdo, 'users', 'full_name')) return "{$alias}.full_name";
        if (saa_col_exists($pdo, 'users', 'username')) return "{$alias}.username";
        if (saa_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");

    saa_add_col($pdo, 'stock_adjustment_headers', 'item_id', "ALTER TABLE stock_adjustment_headers ADD COLUMN item_id INT UNSIGNED NULL AFTER store_id");
    saa_add_col($pdo, 'stock_adjustment_headers', 'unit_cost', "ALTER TABLE stock_adjustment_headers ADD COLUMN unit_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000 AFTER total_qty");
    saa_add_col($pdo, 'stock_adjustment_headers', 'approved_at', "ALTER TABLE stock_adjustment_headers ADD COLUMN approved_at DATETIME NULL AFTER approved_by");
    saa_add_col($pdo, 'stock_adjustment_headers', 'rejected_by', "ALTER TABLE stock_adjustment_headers ADD COLUMN rejected_by INT UNSIGNED NULL AFTER approved_at");
    saa_add_col($pdo, 'stock_adjustment_headers', 'rejected_at', "ALTER TABLE stock_adjustment_headers ADD COLUMN rejected_at DATETIME NULL AFTER rejected_by");
    saa_add_col($pdo, 'stock_adjustment_headers', 'rejected_reason', "ALTER TABLE stock_adjustment_headers ADD COLUMN rejected_reason TEXT NULL AFTER rejected_at");

    try {
        $pdo->exec("ALTER TABLE stock_adjustment_headers MODIFY status ENUM('pending','approved','posted','rejected','void') NOT NULL DEFAULT 'pending'");
    } catch (Throwable $e) {}

} catch (Throwable $e) {
    $errors[] = 'Could not prepare stock adjustment approval tables: ' . $e->getMessage();
}

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

        $action = (string)($_POST['action'] ?? '');
        $adjustmentId = (int)($_POST['adjustment_id'] ?? 0);

        if ($action === 'approve_adjustment') {
            if ($adjustmentId <= 0) throw new RuntimeException('Invalid adjustment selected.');

            if (function_exists('require_permission')) {
                require_permission($pdo, 'stock_movements', 'approve');
            }

            $stmt = $pdo->prepare("
                SELECT ah.*
                FROM stock_adjustment_headers ah
                WHERE ah.id=:id
                LIMIT 1
            ");
            $stmt->execute([':id' => $adjustmentId]);
            $header = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$header) throw new RuntimeException('Adjustment not found.');
            if ($header['status'] !== 'pending') {
                throw new RuntimeException('Only pending adjustments can be approved and posted.');
            }

            $itemId = (int)($header['item_id'] ?? 0);
            if ($itemId <= 0) {
                throw new RuntimeException('Adjustment item is missing. Please recreate the request using the updated stock adjustment page.');
            }

            $stmt = $pdo->prepare("
                SELECT sm.id
                FROM stock_movements sm
                WHERE sm.reference_type='STOCK_ADJUSTMENT'
                  AND sm.reference_id=:id
                LIMIT 1
            ");
            $stmt->execute([':id' => $adjustmentId]);
            if ($stmt->fetchColumn()) {
                throw new RuntimeException('This adjustment has already posted a stock movement.');
            }

            if (!file_exists(__DIR__ . '/../../includes/manager_approval_modal.php')) {
                throw new RuntimeException('Manager approval include is missing: /rooms/includes/manager_approval_modal.php');
            }

            require_once __DIR__ . '/../../includes/manager_approval_modal.php';

            if (!function_exists('require_manager_approval')) {
                throw new RuntimeException('Manager approval function not found.');
            }

            $manager = require_manager_approval(
                $pdo,
                'stock_movements',
                'Approve Stock Adjustment ' . ($header['adjustment_no'] ?? ('#' . $adjustmentId)),
                'stock_adjustment',
                $adjustmentId
            );
            $managerApprovedBy = (int)($manager['id'] ?? 0);

            $stmt = $pdo->prepare("
                SELECT ii.*, COALESCE(NULLIF(ii.avg_cost,0), ii.cost_price, 0) AS resolved_cost
                FROM inventory_items ii
                WHERE ii.id=:id
                  AND ii.is_active=1
                  AND ii.is_stock_item=1
                LIMIT 1
            ");
            $stmt->execute([':id' => $itemId]);
            $item = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$item) throw new RuntimeException('Stock item not found or inactive.');

            $qty = (float)$header['total_qty'];
            if ($qty <= 0) throw new RuntimeException('Adjustment quantity is invalid.');

            $unitCost = (float)($header['unit_cost'] ?? 0);
            if ($unitCost <= 0) $unitCost = (float)$item['resolved_cost'];

            $balance = saa_stock_balance($pdo, $itemId, (int)$header['store_id']);

            if (in_array($header['adjustment_type'], ['ADJUSTMENT_OUT','WASTAGE'], true) && $balance < $qty) {
                throw new RuntimeException('Insufficient stock. Current balance is ' . money_fmt($balance) . ', requested adjustment is ' . money_fmt($qty) . '.');
            }

            $qtyIn = $header['adjustment_type'] === 'ADJUSTMENT_IN' ? $qty : 0;
            $qtyOut = in_array($header['adjustment_type'], ['ADJUSTMENT_OUT','WASTAGE'], true) ? $qty : 0;
            $totalCost = round($qty * $unitCost, 4);

            $pdo->beginTransaction();

            $stmt = $pdo->prepare("
                INSERT INTO stock_movements
                (item_id, store_id, movement_type, qty_in, qty_out, unit_cost, total_cost, reference_type, reference_id, notes, movement_date)
                VALUES
                (:item_id, :store_id, :movement_type, :qty_in, :qty_out, :unit_cost, :total_cost, 'STOCK_ADJUSTMENT', :reference_id, :notes, NOW())
            ");
            $stmt->execute([
                ':item_id' => $itemId,
                ':store_id' => (int)$header['store_id'],
                ':movement_type' => $header['adjustment_type'],
                ':qty_in' => $qtyIn,
                ':qty_out' => $qtyOut,
                ':unit_cost' => $unitCost,
                ':total_cost' => $totalCost,
                ':reference_id' => $adjustmentId,
                ':notes' => $header['reason'] . (!empty($header['notes']) ? ' - ' . $header['notes'] : ''),
            ]);

            if ($header['adjustment_type'] === 'ADJUSTMENT_IN' && $unitCost > 0) {
                $oldQty = max(0, $balance);
                $oldCost = (float)$item['resolved_cost'];
                $newAvg = (($oldQty * $oldCost) + ($qty * $unitCost)) / max(1, ($oldQty + $qty));

                $stmt = $pdo->prepare("UPDATE inventory_items SET avg_cost=:avg_cost, cost_price=:cost_price WHERE id=:id");
                $stmt->execute([
                    ':avg_cost' => $newAvg,
                    ':cost_price' => $unitCost,
                    ':id' => $itemId,
                ]);
            }

            $stmt = $pdo->prepare("
                UPDATE stock_adjustment_headers
                SET status='posted',
                    approved_by=:approved_by,
                    approved_at=NOW(),
                    unit_cost=:unit_cost,
                    total_cost=:total_cost,
                    updated_at=NOW()
                WHERE id=:id
            ");
            $stmt->execute([
                ':approved_by' => $managerApprovedBy ?: ($_SESSION['user_id'] ?? null),
                ':unit_cost' => $unitCost,
                ':total_cost' => $totalCost,
                ':id' => $adjustmentId,
            ]);

            $pdo->commit();

            saa_flash('success', 'Adjustment approved and posted successfully.');
            header('Location: stock_adjustment_approvals.php?adjustment_id=' . $adjustmentId);
            exit;
        }

        if ($action === 'reject_adjustment') {
            if ($adjustmentId <= 0) throw new RuntimeException('Invalid adjustment selected.');

            if (function_exists('require_permission')) {
                require_permission($pdo, 'stock_movements', 'approve');
            }

            $reason = trim((string)($_POST['rejected_reason'] ?? ''));
            if ($reason === '') throw new RuntimeException('Rejection reason is required.');

            $stmt = $pdo->prepare("SELECT * FROM stock_adjustment_headers WHERE id=:id LIMIT 1");
            $stmt->execute([':id' => $adjustmentId]);
            $header = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$header) throw new RuntimeException('Adjustment not found.');
            if ($header['status'] !== 'pending') throw new RuntimeException('Only pending adjustments can be rejected.');

            $stmt = $pdo->prepare("
                UPDATE stock_adjustment_headers
                SET status='rejected',
                    rejected_by=:rejected_by,
                    rejected_at=NOW(),
                    rejected_reason=:rejected_reason,
                    updated_at=NOW()
                WHERE id=:id
            ");
            $stmt->execute([
                ':rejected_by' => $_SESSION['user_id'] ?? null,
                ':rejected_reason' => $reason,
                ':id' => $adjustmentId,
            ]);

            saa_flash('warning', 'Adjustment rejected.');
            header('Location: stock_adjustment_approvals.php?adjustment_id=' . $adjustmentId);
            exit;
        }

    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        saa_flash('danger', $e->getMessage());
        header('Location: stock_adjustment_approvals.php' . ($adjustmentId > 0 ? '?adjustment_id=' . $adjustmentId : ''));
        exit;
    }
}

$status = trim((string)($_GET['status'] ?? 'pending'));
$search = trim((string)($_GET['q'] ?? ''));
$storeId = (int)($_GET['store_id'] ?? 0);

$where = "1=1";
$params = [];

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

$stores = [];
$adjustments = [];
$summary = ['pending'=>0, 'posted'=>0, 'rejected'=>0, 'total_value'=>0];
$viewAdjustment = null;
$viewMovement = null;

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

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

    $userJoins = saa_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,
            {$createdByName} AS created_by_name,
            {$approvedByName} AS approved_by_name,
            {$rejectedByName} AS rejected_by_name,
            ii.item_name,
            ii.item_code,
            u.unit_code,
            sm.id AS movement_id,
            sm.qty_in,
            sm.qty_out,
            sm.unit_cost AS posted_unit_cost,
            sm.total_cost AS posted_total_cost
        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
        LEFT JOIN stock_movements sm ON sm.reference_type='STOCK_ADJUSTMENT' AND sm.reference_id=ah.id
        {$userJoins}
        WHERE {$where}
        ORDER BY
            CASE ah.status WHEN 'pending' THEN 0 WHEN 'posted' THEN 1 WHEN 'rejected' THEN 2 ELSE 3 END,
            ah.created_at DESC,
            ah.id DESC
        LIMIT 500
    ");
    $stmt->execute($params);
    $adjustments = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt = $pdo->query("
        SELECT status, COUNT(*) AS cnt, COALESCE(SUM(total_cost),0) AS total_value
        FROM stock_adjustment_headers
        GROUP BY status
    ");
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $summary[$row['status']] = (int)$row['cnt'];
        $summary['total_value'] += (float)$row['total_value'];
    }

    $viewId = (int)($_GET['adjustment_id'] ?? 0);
    if ($viewId > 0) {
        $stmt = $pdo->prepare("
            SELECT
                ah.*,
                sl.location_name,
                {$createdByName} AS created_by_name,
                {$approvedByName} AS approved_by_name,
                {$rejectedByName} AS rejected_by_name,
                ii.item_name,
                ii.item_code,
                ii.avg_cost,
                ii.cost_price,
                u.unit_code
            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 ah.id=:id
            LIMIT 1
        ");
        $stmt->execute([':id' => $viewId]);
        $viewAdjustment = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;

        $stmt = $pdo->prepare("
            SELECT sm.*, ii.item_name, ii.item_code, u.unit_code
            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
            WHERE sm.reference_type='STOCK_ADJUSTMENT'
              AND sm.reference_id=:id
            LIMIT 1
        ");
        $stmt->execute([':id' => $viewId]);
        $viewMovement = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    }

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

$flashes = saa_get_flash();

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 Approval Control</div>
            <div class="hero-title mt-2">Stock Adjustment Approvals</div>
            <div class="hero-subtitle mt-2">
                Approve pending adjustment requests and post them into stock movements.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="stock_adjustments.php" class="btn btn-light me-2"><i class="bi bi-sliders me-2"></i>Stock Adjustments</a>
            <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 foreach ($flashes as $flash): ?>
    <div class="alert alert-<?php echo h($flash['type']); ?> no-print"><?php echo h($flash['message']); ?></div>
<?php endforeach; ?>

<?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="row g-4 mb-4 no-print">
    <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-hourglass-split"></i></div><div><div class="metric-label">Pending</div><div class="metric-value"><?php echo (int)$summary['pending']; ?></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-check-circle"></i></div><div><div class="metric-label">Posted</div><div class="metric-value"><?php echo (int)$summary['posted']; ?></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-x-circle"></i></div><div><div class="metric-label">Rejected</div><div class="metric-value"><?php echo (int)$summary['rejected']; ?></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-cash-stack"></i></div><div><div class="metric-label">Total Value</div><div class="metric-value small-value"><?php echo money_fmt($summary['total_value']); ?></div></div></div></div>
</div>

<?php if ($viewAdjustment): ?>
<div class="card panel-card mb-4 approval-detail">
    <div class="card-header d-flex justify-content-between align-items-center">
        <div>
            <h5 class="mb-0"><?php echo h($viewAdjustment['adjustment_no']); ?></h5>
            <div class="small text-muted"><?php echo h($viewAdjustment['location_name']); ?> • <?php echo h($viewAdjustment['adjustment_date']); ?></div>
        </div>
        <a href="stock_adjustment_approvals.php" class="btn btn-sm btn-outline-secondary no-print">Close</a>
    </div>
    <div class="card-body">
        <div class="row g-3 mb-3">
            <div class="col-md-3"><strong>Status</strong><br>
                <span class="badge <?php echo $viewAdjustment['status'] === 'pending' ? 'text-bg-warning' : ($viewAdjustment['status'] === 'posted' ? 'text-bg-success' : 'text-bg-danger'); ?>">
                    <?php echo h(ucwords($viewAdjustment['status'])); ?>
                </span>
            </div>
            <div class="col-md-3"><strong>Type</strong><br><?php echo h(str_replace('_',' ', $viewAdjustment['adjustment_type'])); ?></div>
            <div class="col-md-3"><strong>Item</strong><br><?php echo h($viewAdjustment['item_name'] ?: 'Item not found'); ?></div>
            <div class="col-md-3 text-md-end"><strong>Value</strong><br><?php echo money_fmt($viewAdjustment['total_cost']); ?></div>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-md-3"><strong>Qty</strong><br><?php echo money_fmt($viewAdjustment['total_qty']); ?> <?php echo h($viewAdjustment['unit_code'] ?? ''); ?></div>
            <div class="col-md-3"><strong>Unit Cost</strong><br><?php echo money_fmt($viewAdjustment['unit_cost']); ?></div>
            <div class="col-md-3"><strong>Requested By</strong><br><?php echo h($viewAdjustment['created_by_name'] ?: 'User'); ?></div>
            <div class="col-md-3 text-md-end"><strong>Created</strong><br><?php echo h($viewAdjustment['created_at']); ?></div>
        </div>

        <div class="alert alert-light border">
            <strong>Reason:</strong><br><?php echo nl2br(h($viewAdjustment['reason'])); ?>
            <?php if (!empty($viewAdjustment['notes'])): ?>
                <hr><?php echo nl2br(h($viewAdjustment['notes'])); ?>
            <?php endif; ?>
        </div>

        <?php if ($viewMovement): ?>
            <h6 class="fw-bold">Posted Movement</h6>
            <div class="table-responsive mb-4">
                <table class="table table-sm">
                    <thead><tr><th>Item</th><th>Movement</th><th class="text-end">Qty In</th><th class="text-end">Qty Out</th><th class="text-end">Cost</th></tr></thead>
                    <tbody>
                    <tr>
                        <td><strong><?php echo h($viewMovement['item_name']); ?></strong><div class="small text-muted"><?php echo h($viewMovement['item_code'] ?? ''); ?></div></td>
                        <td><?php echo h(str_replace('_',' ', $viewMovement['movement_type'])); ?></td>
                        <td class="text-end"><?php echo money_fmt($viewMovement['qty_in']); ?></td>
                        <td class="text-end"><?php echo money_fmt($viewMovement['qty_out']); ?></td>
                        <td class="text-end"><?php echo money_fmt($viewMovement['total_cost']); ?></td>
                    </tr>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>

        <?php if (!empty($viewAdjustment['rejected_reason'])): ?>
            <div class="alert alert-danger">
                <strong>Rejected reason:</strong><br><?php echo nl2br(h($viewAdjustment['rejected_reason'])); ?>
            </div>
        <?php endif; ?>
    </div>
</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-3">
                <label class="form-label">Status</label>
                <select name="status" class="form-select">
                    <option value="">All</option>
                    <option value="pending" <?php echo $status === 'pending' ? 'selected' : ''; ?>>Pending</option>
                    <option value="posted" <?php echo $status === 'posted' ? 'selected' : ''; ?>>Posted</option>
                    <option value="rejected" <?php echo $status === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                    <option value="void" <?php echo $status === 'void' ? 'selected' : ''; ?>>Void</option>
                </select>
            </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-4">
                <label class="form-label">Search</label>
                <input type="text" name="q" class="form-control" value="<?php echo h($search); ?>" placeholder="No / reason / item / store">
            </div>
            <div class="col-md-2 d-grid">
                <button class="btn btn-primary"><i class="bi bi-funnel me-2"></i>Filter</button>
            </div>
        </form>
    </div>
</div>

<div class="card panel-card no-print">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Adjustment Requests</h5>
        <span class="small text-muted">Showing latest 500</span>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-modern align-middle mb-0">
                <thead>
                <tr>
                    <th>Date</th>
                    <th>No</th>
                    <th>Store</th>
                    <th>Item</th>
                    <th>Type</th>
                    <th class="text-end">Qty</th>
                    <th class="text-end">Value</th>
                    <th>Status</th>
                    <th>Reason</th>
                    <th class="text-end">Action</th>
                </tr>
                </thead>
                <tbody>
                <?php if (!$adjustments): ?>
                    <tr><td colspan="10" class="text-center text-muted py-4">No stock adjustment requests found.</td></tr>
                <?php else: foreach ($adjustments as $a): ?>
                    <?php $rowClass = $a['status'] === 'pending' ? 'table-warning' : ($a['status'] === 'rejected' ? 'table-danger' : ''); ?>
                    <tr class="<?php echo h($rowClass); ?>">
                        <td><?php echo h($a['adjustment_date']); ?></td>
                        <td><strong><?php echo h($a['adjustment_no']); ?></strong><div class="small text-muted"><?php echo h(date('Y-m-d H:i', strtotime($a['created_at']))); ?></div></td>
                        <td><?php echo h($a['location_name']); ?></td>
                        <td>
                            <strong><?php echo h($a['item_name'] ?: 'Item missing'); ?></strong>
                            <div class="small text-muted"><?php echo h($a['item_code'] ?? ''); ?></div>
                        </td>
                        <td><span class="badge <?php echo $a['adjustment_type'] === 'ADJUSTMENT_IN' ? 'text-bg-success' : 'text-bg-warning'; ?>"><?php echo h(str_replace('_',' ', $a['adjustment_type'])); ?></span></td>
                        <td class="text-end"><?php echo money_fmt($a['total_qty']); ?> <?php echo h($a['unit_code'] ?? ''); ?></td>
                        <td class="text-end"><?php echo money_fmt($a['status'] === 'posted' && $a['posted_total_cost'] !== null ? $a['posted_total_cost'] : $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 class="small"><?php echo h(mb_strimwidth((string)$a['reason'], 0, 80, '...')); ?></td>
                        <td class="text-end">
                            <div class="btn-group btn-group-sm">
                                <a href="stock_adjustment_approvals.php?adjustment_id=<?php echo (int)$a['id']; ?>" class="btn btn-outline-primary">
                                    <i class="bi bi-eye"></i>
                                </a>

                                <?php if ($a['status'] === 'pending'): ?>
                                    <form method="post" id="approveAdjustmentForm<?php echo (int)$a['id']; ?>" class="d-inline">
                                        <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                        <input type="hidden" name="action" value="approve_adjustment">
                                        <input type="hidden" name="adjustment_id" value="<?php echo (int)$a['id']; ?>">
                                        <input type="hidden" name="manager_approved" value="0">
                                        <input type="hidden" name="manager_password" value="">
                                        <button type="button"
                                                class="btn btn-outline-success manager-approval-trigger"
                                                data-action-title="Approve Stock Adjustment <?php echo h($a['adjustment_no']); ?>"
                                                data-action-message="Manager approval is required before this adjustment posts into stock movements."
                                                data-target-form="#approveAdjustmentForm<?php echo (int)$a['id']; ?>">
                                            <i class="bi bi-check-circle"></i>
                                        </button>
                                    </form>

                                    <button class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#rejectModal<?php echo (int)$a['id']; ?>">
                                        <i class="bi bi-x-circle"></i>
                                    </button>

                                    <div class="modal fade text-start" id="rejectModal<?php echo (int)$a['id']; ?>" tabindex="-1" aria-hidden="true">
                                        <div class="modal-dialog modal-dialog-centered">
                                            <div class="modal-content">
                                                <form method="post">
                                                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                    <input type="hidden" name="action" value="reject_adjustment">
                                                    <input type="hidden" name="adjustment_id" value="<?php echo (int)$a['id']; ?>">
                                                    <div class="modal-header">
                                                        <h5 class="modal-title">Reject <?php echo h($a['adjustment_no']); ?></h5>
                                                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                    </div>
                                                    <div class="modal-body">
                                                        <label class="form-label">Rejection Reason</label>
                                                        <textarea name="rejected_reason" class="form-control" rows="4" required></textarea>
                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                                                        <button class="btn btn-danger">Reject Adjustment</button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<style>
.small-value{font-size:1rem!important;letter-spacing:0!important}
.approval-detail{border:2px solid rgba(37,99,235,.18)}
@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}
}
</style>

<?php
if (file_exists(__DIR__ . '/../../includes/manager_approval_modal.php')) {
    require_once __DIR__ . '/../../includes/manager_approval_modal.php';
}
require_once __DIR__ . '/../../includes/footer.php';
?>
