<?php
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Enable error reporting for development
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors on page
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');

require_once('../includes/admin-security.php');
include_once('includes/config.php');

// Access Check
if (!has_permission('manage_inventory')) {
    echo "<script>alert('Access Denied. Redirecting to Dashboard...'); window.location.href='dashboard.php';</script>";
    exit();
}

$adminId = $_SESSION['aid'];

// Handle Stock Update
if (isset($_POST['update_stock'])) {
    $productId = intval($_POST['product_id']);
    $adjustmentType = $_POST['adjustment_type'];
    $quantity = intval($_POST['quantity']);
    $reason = mysqli_real_escape_string($con, $_POST['reason']);

    if ($quantity > 0) {
        $checkProduct = mysqli_query($con, "SELECT stock_quantity, vendor_id FROM products WHERE id='$productId'");
        if (mysqli_num_rows($checkProduct) > 0) {
            $row = mysqli_fetch_assoc($checkProduct);
            $currentStock = intval($row['stock_quantity']);
            $pVendorId = isset($row['vendor_id']) ? $row['vendor_id'] : 0;

            $adjustment = ($adjustmentType == 'add') ? $quantity : -$quantity;
            $newStock = $currentStock + $adjustment;

            if ($newStock < 0) {
                $_SESSION['error'] = "Error: Cannot remove more stock than available.";
            } else {
                mysqli_query($con, "UPDATE products SET stock_quantity='$newStock', updationDate=NOW() WHERE id='$productId'");

                // Log (Using Admin ID as created_by)
                mysqli_query($con, "INSERT INTO inventory_logs 
                    (product_id, vendor_id, adjustment, previous_stock, current_stock, reason, created_by) 
                    VALUES ('$productId', '$pVendorId', '$adjustment', '$currentStock', '$newStock', '$reason (Admin)', '$adminId')");

                $_SESSION['msg'] = "Stock updated successfully!";
            }
        }
    }
    header("Location: inventory.php");
    exit();
}

// Filtration
$filterVendor = isset($_GET['vendor']) ? $_GET['vendor'] : 'all';
$query = "SELECT p.*, v.store_name FROM products p LEFT JOIN vendors v ON p.vendor_id = v.id WHERE 1=1";

if ($filterVendor == 'mine') {
    $query .= " AND (p.vendor_id IS NULL OR p.vendor_id=0)";
    $pageTitleSuffix = " (Official Store)";
} elseif (is_numeric($filterVendor)) {
    $vid = intval($filterVendor);
    $query .= " AND p.vendor_id='$vid'";
    $pageTitleSuffix = " (Vendor #$vid)";
} else {
    $pageTitleSuffix = " (All Products)";
}
$query .= " ORDER BY p.id DESC";
$result = mysqli_query($con, $query);

// Get Statistics
$totalProducts = mysqli_num_rows(mysqli_query($con, "SELECT id FROM products"));
$lowStockCount = mysqli_num_rows(mysqli_query($con, "SELECT id FROM products WHERE stock_quantity > 0 AND stock_quantity < 10"));
$outOfStockCount = mysqli_num_rows(mysqli_query($con, "SELECT id FROM products WHERE stock_quantity = 0"));

// Get Vendors for Dropdown
$vendorsList = mysqli_query($con, "SELECT id, store_name FROM vendors");
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title>Inventory Management - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" />
    <link href="css/styles.css?v=4.0" rel="stylesheet" />
    <link href="css/admin-professional.css?v=4.0" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"></script>

</head>

<body class="sb-nav-fixed">
    <?php include_once('includes/header.php'); ?>
    <div id="layoutSidenav">
        <?php include_once('includes/sidebar.php'); ?>
        <div id="layoutSidenav_content">
            <main>
                <div class="container-fluid px-4">
                    <div class="page-header mt-4 d-flex justify-content-between align-items-center">
                        <div>
                            <h1><i class="fas fa-boxes me-2"></i> Inventory Mgmt</h1>
                            <p class="mb-0">Manage stock across the platform</p>
                        </div>
                        <div>
                            <a href="../vendor-store.php?vid=0" target="_blank"
                                class="btn btn-outline-primary">
                                <i class="fas fa-store me-2"></i>View Official Store
                            </a>
                        </div>
                    </div>

                    <?php if (isset($_SESSION['msg'])) { ?>
                        <div class="alert alert-success alert-dismissible fade show">
                            <?php echo $_SESSION['msg'];
                            unset($_SESSION['msg']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php } ?>

                    <div class="row mb-4">
                        <div class="col-md-4">
                            <div class="stat-mini">
                                <div class="icon"><i class="fas fa-boxes"></i></div>
                                <div class="details">
                                    <div class="label">Total Products</div>
                                    <div class="value"><?php echo $totalProducts; ?></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="stat-mini border-warning">
                                <div class="icon text-warning"><i class="fas fa-exclamation-triangle"></i></div>
                                <div class="details">
                                    <div class="label">Low Stock Items</div>
                                    <div class="value text-warning"><?php echo $lowStockCount; ?></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="stat-mini border-danger">
                                <div class="icon text-danger"><i class="fas fa-times-circle"></i></div>
                                <div class="details">
                                    <div class="label">Out of Stock</div>
                                    <div class="value text-danger"><?php echo $outOfStockCount; ?></div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter & Actions Bar -->
                    <div class="card mb-4 border-0 shadow-sm">
                        <div class="card-body p-3">
                            <form method="get" class="row g-3 align-items-center">
                                <div class="col-md-4">
                                    <div class="input-group">
                                        <span class="input-group-text bg-white border-end-0">
                                            <i class="fas fa-filter text-muted"></i>
                                        </span>
                                        <select name="vendor" class="form-select border-start-0 ps-0"
                                            onchange="this.form.submit()">
                                            <option value="all" <?php if ($filterVendor == 'all')
                                                echo 'selected'; ?>>All
                                                Sources</option>
                                            <option value="mine" <?php if ($filterVendor == 'mine')
                                                echo 'selected'; ?>>
                                                Official Mall Products</option>
                                            <option disabled>──────────────</option>
                                            <?php
                                            mysqli_data_seek($vendorsList, 0);
                                            while ($v = mysqli_fetch_array($vendorsList)) { ?>
                                                <option value="<?php echo $v['id']; ?>" <?php if ($filterVendor == $v['id'])
                                                       echo 'selected'; ?>>
                                                    <?php echo htmlentities($v['store_name']); ?>
                                                </option>
                                            <?php } ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-8 text-end">
                                    <a href="inventory-history.php" class="btn btn-outline-secondary me-2">
                                        <i class="fas fa-history me-2"></i>Inventory Logs
                                    </a>
                                    <button type="button" class="btn btn-primary" onclick="window.location.reload();">
                                        <i class="fas fa-sync-alt"></i>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <div class="table-card">
                        <table id="datatablesSimple" class="table table-hover">
                            <thead>
                                <tr>
                                    <th width="5%">#</th>
                                    <th>Product Details</th>
                                    <th>Vendor / Source</th>
                                    <th class="text-center">Stock</th>
                                    <th>Status</th>
                                    <th class="text-center">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $cnt = 1;
                                while ($row = mysqli_fetch_array($result)) {
                                    $stock = intval($row['stock_quantity']);

                                    // Status configuration
                                    if ($stock == 0) {
                                        $statusClass = 'cancelled'; // Using professional theme class names
                                        $statusText = 'Out of Stock';
                                    } elseif ($stock < 10) {
                                        $statusClass = 'pending';
                                        $statusText = 'Low Stock';
                                    } else {
                                        $statusClass = 'delivered';
                                        $statusText = 'In Stock';
                                    }

                                    $vendorName = ($row['store_name']) ? htmlentities($row['store_name']) : 'Official Mall';
                                    $vendorBadge = ($row['store_name']) ? 'bg-light text-dark border' : 'bg-primary text-white';

                                    // Image path with fallback
                                    $imagePath = "productimages/" . $row['id'] . "/" . $row['productImage1'];
                                    $imageExists = !empty($row['productImage1']) && file_exists($imagePath);
                                    ?>
                                    <tr>
                                        <td><?php echo $cnt; ?></td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="product-thumb me-3"
                                                    style="width: 40px; height: 40px; flex-shrink: 0;">
                                                    <?php if ($imageExists) { ?>
                                                        <img src="<?php echo $imagePath; ?>" class="rounded border"
                                                            style="width: 100%; height: 100%; object-fit: cover;">
                                                    <?php } else { ?>
                                                        <div
                                                            class="bg-light rounded border d-flex align-items-center justify-content-center w-100 h-100">
                                                            <i class="fas fa-image text-muted opacity-50 small"></i>
                                                        </div>
                                                    <?php } ?>
                                                </div>
                                                <div>
                                                    <div class="fw-bold text-dark">
                                                        <?php echo htmlentities($row['productName']); ?></div>
                                                    <small class="text-muted">ID: <?php echo $row['id']; ?></small>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="badge <?php echo $vendorBadge; ?> fw-normal">
                                                <?php echo $vendorName; ?>
                                            </span>
                                        </td>
                                        <td class="text-center">
                                            <span class="fw-bold <?php echo ($stock < 10) ? 'text-danger' : ''; ?>">
                                                <?php echo $stock; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="status-badge <?php echo $statusClass; ?>">
                                                <?php echo $statusText; ?>
                                            </span>
                                        </td>
                                        <td class="text-center">
                                            <button type="button" class="btn btn-sm btn-outline-primary"
                                                data-bs-toggle="modal" data-bs-target="#stockModal"
                                                data-id="<?php echo $row['id']; ?>"
                                                data-name="<?php echo htmlentities($row['productName']); ?>"
                                                data-stock="<?php echo $stock; ?>">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php $cnt++;
                                } ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </main>
            <?php include_once('includes/footer.php'); ?>
        </div>
    </div>

    <!-- Update Stock Modal -->
    <div class="modal fade" id="stockModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="post">
                    <div class="modal-header">
                        <h5 class="modal-title">Adjust Stock</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="product_id" id="modal_product_id">
                        <div class="mb-3">
                            <label class="form-label">Product:</label>
                            <input type="text" class="form-control" id="modal_product_name" readonly>
                        </div>
                        <div class="row">
                            <div class="col-6 mb-3">
                                <label class="form-label">Current:</label>
                                <input type="text" class="form-control" id="modal_current_stock" readonly>
                            </div>
                            <div class="col-6 mb-3">
                                <label class="form-label">Action:</label>
                                <select name="adjustment_type" class="form-select" required>
                                    <option value="add">Add (+)</option>
                                    <option value="remove">Remove (-)</option>
                                </select>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Quantity:</label>
                            <input type="number" name="quantity" class="form-control" min="1" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Reason:</label>
                            <input type="text" name="reason" class="form-control" placeholder="Optional reason">
                        </div>
                    </div>
                    <div class="modal-footer border-0">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="update_stock" class="btn btn-primary px-4">Update Inventory</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="js/scripts.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/simple-datatables@latest"></script>
    <script src="js/datatables-simple-demo.js"></script>
    <script>
        var stockModal = document.getElementById('stockModal');
        stockModal.addEventListener('show.bs.modal', function (event) {
            var button = event.relatedTarget;
            var id = button.getAttribute('data-id');
            var name = button.getAttribute('data-name');
            var stock = button.getAttribute('data-stock');
            stockModal.querySelector('#modal_product_id').value = id;
            stockModal.querySelector('#modal_product_name').value = name;
            stockModal.querySelector('#modal_current_stock').value = stock;
        });
    </script>
</body>

</html>