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

$pageTitle = 'Stock Adjustments';

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', '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('sa_flash')) {
    function sa_flash(string $type, string $message): void {
        $_SESSION['stock_adjustment_flash'][] = ['type' => $type, 'message' => $message];
    }
}
if (!function_exists('sa_get_flash')) {
    function sa_get_flash(): array {
        $items = $_SESSION['stock_adjustment_flash'] ?? [];
        unset($_SESSION['stock_adjustment_flash']);
        return $items;
    }
}
if (!function_exists('sa_table_exists')) {
    function sa_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('sa_col_exists')) {
    function sa_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('sa_add_col')) {
    function sa_add_col(PDO $pdo, string $table, string $column, string $sql): void {
        if (!sa_col_exists($pdo, $table, $column)) {
            $pdo->exec($sql);
        }
    }
}
if (!function_exists('sa_stock_balance')) {
    function sa_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('sa_adjustment_no')) {
    function sa_adjustment_no(PDO $pdo): string {
        $prefix = 'ADJ-' . date('ymd') . '-';
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM stock_adjustment_headers WHERE adjustment_no LIKE :p");
        $stmt->execute([':p' => $prefix . '%']);
        return $prefix . str_pad((string)((int)$stmt->fetchColumn() + 1), 4, '0', STR_PAD_LEFT);
    }
}
if (!function_exists('sa_user_name_expr')) {
    function sa_user_name_expr(PDO $pdo, string $alias = 'u'): string {
        if (!sa_table_exists($pdo, 'users')) return "NULL";
        if (sa_col_exists($pdo, 'users', 'firstname') && sa_col_exists($pdo, 'users', 'lastname')) return "CONCAT({$alias}.firstname, ' ', {$alias}.lastname)";
        if (sa_col_exists($pdo, 'users', 'name')) return "{$alias}.name";
        if (sa_col_exists($pdo, 'users', 'full_name')) return "{$alias}.full_name";
        if (sa_col_exists($pdo, 'users', 'username')) return "{$alias}.username";
        if (sa_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_item_categories (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        category_name VARCHAR(120) NOT NULL,
        category_type ENUM('stock','food','bar','curio','consumable','service','other') NOT NULL DEFAULT 'stock',
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_inventory_category_name (category_name)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

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

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

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

    $pdo->exec("CREATE TABLE IF NOT EXISTS 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");

    sa_add_col($pdo, 'stock_adjustment_headers', 'item_id', "ALTER TABLE stock_adjustment_headers ADD COLUMN item_id INT UNSIGNED NULL AFTER store_id");
    sa_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");
    sa_add_col($pdo, 'stock_adjustment_headers', 'approved_at', "ALTER TABLE stock_adjustment_headers ADD COLUMN approved_at DATETIME NULL AFTER approved_by");
    sa_add_col($pdo, 'stock_adjustment_headers', 'rejected_by', "ALTER TABLE stock_adjustment_headers ADD COLUMN rejected_by INT UNSIGNED NULL AFTER approved_at");
    sa_add_col($pdo, 'stock_adjustment_headers', 'rejected_at', "ALTER TABLE stock_adjustment_headers ADD COLUMN rejected_at DATETIME NULL AFTER rejected_by");
    sa_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 tables: ' . $e->getMessage();
}

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

        if (($_POST['action'] ?? '') === 'request_adjustment') {
            if (function_exists('require_permission')) {
                require_permission($pdo, 'stock_movements', 'create');
            }

            $storeId = (int)($_POST['store_id'] ?? 0);
            $itemId = (int)($_POST['item_id'] ?? 0);
            $adjustmentType = (string)($_POST['adjustment_type'] ?? '');
            $qty = (float)($_POST['qty'] ?? 0);
            $unitCost = (float)($_POST['unit_cost'] ?? 0);
            $reason = trim((string)($_POST['reason'] ?? ''));
            $notes = trim((string)($_POST['notes'] ?? ''));

            if ($storeId <= 0) throw new RuntimeException('Please select store.');
            if ($itemId <= 0) throw new RuntimeException('Please select stock item.');
            if (!in_array($adjustmentType, ['ADJUSTMENT_IN','ADJUSTMENT_OUT','WASTAGE'], true)) throw new RuntimeException('Invalid adjustment type.');
            if ($qty <= 0) throw new RuntimeException('Quantity must be greater than zero.');
            if ($reason === '') throw new RuntimeException('Adjustment reason is required.');

            $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 item is not stock controlled.');

            if ($unitCost <= 0) {
                $unitCost = (float)$item['resolved_cost'];
            }

            $currentBalance = sa_stock_balance($pdo, $itemId, $storeId);

            /*
             * Do not block pending request too aggressively, but warn by blocking impossible out/wastage.
             */
            if (in_array($adjustmentType, ['ADJUSTMENT_OUT','WASTAGE'], true) && $currentBalance < $qty) {
                throw new RuntimeException('Insufficient stock. Current balance is ' . money_fmt($currentBalance) . ', requested quantity is ' . money_fmt($qty) . '.');
            }

            $pdo->beginTransaction();

            $adjustmentNo = sa_adjustment_no($pdo);
            $totalCost = round($qty * $unitCost, 4);

            /*
             * IMPORTANT:
             * This creates a PENDING request only.
             * It does NOT post stock_movements.
             * Manager posts it from stock_adjustment_approvals.php.
             */
            $stmt = $pdo->prepare("
                INSERT INTO stock_adjustment_headers
                (adjustment_no, store_id, item_id, adjustment_date, adjustment_type, reason, notes, total_qty, unit_cost, total_cost, status, created_by)
                VALUES
                (:adjustment_no, :store_id, :item_id, CURDATE(), :adjustment_type, :reason, :notes, :total_qty, :unit_cost, :total_cost, 'pending', :created_by)
            ");
            $stmt->execute([
                ':adjustment_no' => $adjustmentNo,
                ':store_id' => $storeId,
                ':item_id' => $itemId,
                ':adjustment_type' => $adjustmentType,
                ':reason' => $reason,
                ':notes' => $notes ?: null,
                ':total_qty' => $qty,
                ':unit_cost' => $unitCost,
                ':total_cost' => $totalCost,
                ':created_by' => $_SESSION['user_id'] ?? null,
            ]);

            $adjustmentId = (int)$pdo->lastInsertId();

            $pdo->commit();

            sa_flash('success', 'Stock adjustment request created successfully: ' . $adjustmentNo . '. It is pending manager approval.');
            header('Location: stock_adjustments.php?adjustment_id=' . $adjustmentId);
            exit;
        }

    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        sa_flash('danger', $e->getMessage());
        header('Location: stock_adjustments.php');
        exit;
    }
}

$stores = [];
$items = [];
$adjustments = [];
$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);

    $items = $pdo->query("
        SELECT
            ii.*,
            c.category_name,
            u.unit_code,
            COALESCE(NULLIF(ii.avg_cost,0), ii.cost_price, 0) AS resolved_cost
        FROM inventory_items ii
        LEFT JOIN inventory_item_categories c ON c.id=ii.category_id
        LEFT JOIN inventory_units u ON u.id=ii.unit_id
        WHERE ii.is_active=1
          AND ii.is_stock_item=1
        ORDER BY ii.item_name ASC
    ")->fetchAll(PDO::FETCH_ASSOC);

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

    $userJoins = sa_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
    " : "";

    $adjustments = $pdo->query("
        SELECT
            ah.*,
            sl.location_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,
            {$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
        LEFT JOIN stock_movements sm ON sm.reference_type='STOCK_ADJUSTMENT' AND sm.reference_id=ah.id
        {$userJoins}
        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 300
    ")->fetchAll(PDO::FETCH_ASSOC);

    $viewId = (int)($_GET['adjustment_id'] ?? 0);
    if ($viewId > 0) {
        $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 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 stock adjustment data: ' . $e->getMessage();
}

$summary = ['pending'=>0,'posted'=>0,'rejected'=>0,'value'=>0];
foreach ($adjustments as $a) {
    if (isset($summary[$a['status']])) $summary[$a['status']]++;
    $summary['value'] += (float)($a['total_cost'] ?? 0);
}

$flashes = sa_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-sliders"></i> Inventory Control</div>
            <div class="hero-title mt-2">Stock Adjustments</div>
            <div class="hero-subtitle mt-2">
                Create stock adjustment requests. Managers approve and post them from the approval screen.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="stock_adjustment_approvals.php" class="btn btn-light me-2">
                <i class="bi bi-shield-check me-2"></i>Approvals
            </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">Request Value</div><div class="metric-value small-value"><?php echo money_fmt($summary['value']); ?></div></div>
        </div>
    </div>
</div>

<?php if ($viewAdjustment): ?>
<div class="card panel-card mb-4 adjustment-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>
        <div class="d-flex gap-2 no-print">
            <button onclick="window.print()" class="btn btn-sm btn-outline-primary"><i class="bi bi-printer me-1"></i>Print</button>
            <a href="stock_adjustments.php" class="btn btn-sm btn-outline-secondary">Close</a>
        </div>
    </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>Total Cost</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): ?>
            <div class="alert alert-success">
                <strong>Posted movement:</strong>
                <?php echo h(str_replace('_',' ', $viewMovement['movement_type'])); ?> —
                Qty In: <?php echo money_fmt($viewMovement['qty_in']); ?>,
                Qty Out: <?php echo money_fmt($viewMovement['qty_out']); ?>
            </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="row g-4">
    <div class="col-xl-4">
        <div class="card panel-card">
            <div class="card-header">
                <h5 class="mb-0">Request Adjustment</h5>
            </div>
            <div class="card-body">
                <form method="post" id="stockAdjustmentRequestForm">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="request_adjustment">

                    <div class="mb-3">
                        <label class="form-label">Store *</label>
                        <select name="store_id" class="form-select" required>
                            <option value="">Select store</option>
                            <?php foreach ($stores as $store): ?>
                                <option value="<?php echo (int)$store['id']; ?>"><?php echo h($store['location_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Stock Item *</label>
                        <select name="item_id" id="itemId" class="form-select" required>
                            <option value="">Select item</option>
                            <?php foreach ($items as $item): ?>
                                <option value="<?php echo (int)$item['id']; ?>"
                                        data-cost="<?php echo h($item['resolved_cost']); ?>">
                                    <?php echo h($item['item_name']); ?>
                                    <?php echo !empty($item['item_code']) ? ' • ' . h($item['item_code']) : ''; ?>
                                    <?php echo !empty($item['unit_code']) ? ' (' . h($item['unit_code']) . ')' : ''; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Adjustment Type *</label>
                        <select name="adjustment_type" class="form-select" required>
                            <option value="ADJUSTMENT_IN">Adjustment In / Found Stock</option>
                            <option value="ADJUSTMENT_OUT">Adjustment Out / Write Off</option>
                            <option value="WASTAGE">Wastage / Spoilage / Breakage</option>
                        </select>
                    </div>

                    <div class="row g-2">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Quantity *</label>
                            <input type="number" step="0.0001" min="0.0001" name="qty" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Unit Cost</label>
                            <input type="number" step="0.0001" min="0" name="unit_cost" id="unitCost" class="form-control">
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Reason *</label>
                        <input type="text" name="reason" class="form-control" required placeholder="e.g. Breakage, expired, stock count correction">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Notes</label>
                        <textarea name="notes" class="form-control" rows="3"></textarea>
                    </div>

                    <button class="btn btn-primary w-100">
                        <i class="bi bi-send-check me-2"></i>Submit Request
                    </button>
                </form>
            </div>
        </div>

        <div class="alert alert-info mt-4">
            <strong>New flow:</strong> This page creates a pending request only. A manager approves and posts it from <strong>Stock Adjustment Approvals</strong>.
        </div>
    </div>

    <div class="col-xl-8">
        <div class="card panel-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Recent Adjustment Requests</h5>
                <a href="stock_adjustment_approvals.php" class="btn btn-sm btn-outline-primary no-print">
                    <i class="bi bi-shield-check me-1"></i>Approvals
                </a>
            </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">View</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$adjustments): ?>
                            <tr><td colspan="10" class="text-center text-muted py-4">No adjustments requested yet.</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['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 not found'); ?></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['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, 60, '...')); ?></td>
                                <td class="text-end">
                                    <a href="stock_adjustments.php?adjustment_id=<?php echo (int)$a['id']; ?>" class="btn btn-sm btn-outline-primary">
                                        <i class="bi bi-eye"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<style>
.small-value{font-size:1rem!important;letter-spacing:0!important}
.adjustment-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>
<script>
document.addEventListener('DOMContentLoaded', function(){
    const itemSelect = document.getElementById('itemId');
    const unitCost = document.getElementById('unitCost');
    if (itemSelect && unitCost) {
        itemSelect.addEventListener('change', function(){
            const opt = this.options[this.selectedIndex];
            unitCost.value = opt && opt.dataset.cost ? parseFloat(opt.dataset.cost || '0').toFixed(4) : '';
        });
    }
});
</script>
<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
