<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();

require_once '../config.php';

$active = 'wholesaler';

$message = '';
$messageType = '';

/*
|--------------------------------------------------------------------------
| Delete record
|--------------------------------------------------------------------------
*/
if (isset($_GET['delete'])) {
    $deleteId = (int) $_GET['delete'];

    $stmt = $conn->prepare("DELETE FROM wholesaler WHERE id = ?");
    if ($stmt) {
        $stmt->bind_param("i", $deleteId);
       if ($stmt->execute()) {

    $_SESSION['success_message'] = 'Wholesaler stock saved successfully.';

    header("Location: wholesaler.php");
    exit;

} else {
    $message = 'Save failed.';
    $messageType = 'danger';
}
        $stmt->close();
    } else {
        $message = 'Delete query failed.';
        $messageType = 'danger';
    }
}

/*
|--------------------------------------------------------------------------
| Save record
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_wholesaler'])) {
    $product_id    = (int)($_POST['product_id'] ?? 0);
    $sale_month    = trim($_POST['sale_month'] ?? '');
    $initial_stock = (int)($_POST['initial_stock'] ?? 0);
    $month_sales   = (int)($_POST['month_sales'] ?? 0);
    $balance_stock = $initial_stock - $month_sales;

    if ($product_id <= 0 || $sale_month === '') {
        $message = 'Please select product and month.';
        $messageType = 'warning';
    } else {
        $stmt = $conn->prepare("
            INSERT INTO wholesaler
                (product_id, sale_month, initial_stock, month_sales, balance_stock, created_at)
            VALUES
                (?, ?, ?, ?, ?, NOW())
        ");

        if ($stmt) {
            $stmt->bind_param("isiii", $product_id, $sale_month, $initial_stock, $month_sales, $balance_stock);

            if ($stmt->execute()) {
                $message = 'Wholesaler stock saved successfully.';
                $messageType = 'success';
            } else {
                $message = 'Save failed.';
                $messageType = 'danger';
            }
            $stmt->close();
        } else {
            $message = 'Insert query failed.';
            $messageType = 'danger';
        }
    }
}

/*
|--------------------------------------------------------------------------
| Product list
|--------------------------------------------------------------------------
*/
$products = [];
$productSql = "SELECT id, product_name FROM products ORDER BY product_name ASC";
$productQuery = $conn->query($productSql);

if ($productQuery) {
    while ($row = $productQuery->fetch_assoc()) {
        $products[] = $row;
    }
} else {
    $message = 'Products table query failed. Check column name product_name.';
    $messageType = 'warning';
}

/*
|--------------------------------------------------------------------------
| Records list
|--------------------------------------------------------------------------
*/
$records = [];
$listSql = "
    SELECT
        w.id,
        w.sale_month,
        w.initial_stock,
        w.month_sales,
        w.balance_stock,
        w.created_at,
        p.product_name
    FROM wholesaler w
    LEFT JOIN products p ON p.id = w.product_id
    ORDER BY w.id DESC
";
$listQuery = $conn->query($listSql);

if ($listQuery) {
    while ($row = $listQuery->fetch_assoc()) {
        $records[] = $row;
    }
}

/*
|--------------------------------------------------------------------------
| Sidebar/Header includes
|--------------------------------------------------------------------------
*/
$sidebarFile = __DIR__ . '/agencysidebar.php';
$headerFile  = __DIR__ . '/../header.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wholesaler Page</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
   <style>
    body {
        background: #f1f5f9;
        font-family: 'Segoe UI', sans-serif;
    }

    .main-area {
        min-height: 100vh;
        width: 100%;
        padding-left: 260px;
        padding-top: 85px;
    }

    .content-wrap {
        padding: 25px;
    }

  .top-card {
    background: #374155;
    border-radius: 16px;
    padding: 20px;
    color: white;
    margin-bottom: 18px;
    box-shadow: 0 6px 18px rgba(0,0,0,.12);
}

    .top-card h2 {
    font-size: 20px;
    font-weight: 700;
    margin-bottom: 4px;
}

    .top-card p {
    margin: 0;
    opacity: .9;
    font-size: 13px;
}

   .page-card {
    border: none;
    border-radius: 16px;
    background: #fff;
    box-shadow: 0 4px 16px rgba(0,0,0,.05);
    overflow: hidden;
}

    .card-header-custom {
        background: #fff;
        padding: 20px 25px;
        border-bottom: 1px solid #eef2f7;
        font-size: 20px;
        font-weight: 700;
    }

 .form-control,
.form-select {
    border-radius: 10px;
    min-height: 42px;
    border: 1px solid #dbe2ea;
    font-size: 14px;
}

    .form-control:focus,
    .form-select:focus {
        box-shadow: 0 0 0 0.2rem rgba(37,99,235,.15);
        border-color: #2563eb;
    }
.btn-primary {
    background: #374155;
    border: none;
    border-radius: 10px;
    padding: 10px 22px;
    font-weight: 600;
    font-size: 14px;
}

    .btn-danger {
        border-radius: 12px;
    }

.table thead th {
    background: #f8fafc;
    border: none;
    font-size: 13px;
    color: #475569;
    padding: 12px;
}
    .table tbody td {
    padding: 12px;
    vertical-align: middle;
    font-size: 14px;
}

    .badge-month {
        background: #dbeafe;
        color: #1d4ed8;
        padding: 8px 12px;
        border-radius: 30px;
        font-weight: 600;
    }

    .stock-badge {
        background: #dcfce7;
        color: #15803d;
        padding: 7px 14px;
        border-radius: 30px;
        font-weight: 600;
    }

    .sales-badge {
        background: #fee2e2;
        color: #dc2626;
        padding: 7px 14px;
        border-radius: 30px;
        font-weight: 600;
    }

    @media (max-width: 991px) {
        .main-area {
            padding-left: 0;
            padding-top: 20px;
        }

        .content-wrap {
            padding: 18px;
        }

        .top-card h2 {
            font-size: 24px;
        }
    }
</style>
</head>
<body>

<?php if (file_exists($sidebarFile)) { include $sidebarFile; } ?>
<?php if (file_exists($headerFile)) { include $headerFile; } ?>

<div class="main-area">
    <div class="content-wrap">
        <div class="container-fluid">
    <div class="top-card">
    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
        <div>
            <h2>
                <i class="fa-solid fa-boxes-stacked me-2"></i>
                Wholesaler Dashboard
            </h2>

            <p>
                Manage product stock, monthly sales and balance inventory
            </p>
        </div>

        <div class="text-end">
            <i class="fa-solid fa-chart-line fa-2x opacity-75"></i>
        </div>
    </div>
</div>

            <?php if ($message): ?>
                <div class="alert alert-<?= htmlspecialchars($messageType) ?> alert-dismissible fade show" role="alert">
                    <?= htmlspecialchars($message) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <div class="card page-card mb-4">
                <div class="card-body p-4">
                    <form method="POST" id="wholesalerForm">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label">Product</label>
                                <select name="product_id" class="form-select" required>
                                    <option value="">Select Product</option>
                                    <?php foreach ($products as $p): ?>
                                        <option value="<?= (int)$p['id'] ?>"><?= htmlspecialchars($p['product_name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="col-md-4">
                                <label class="form-label">Month</label>
                                <input type="month" name="sale_month" class="form-control" required>
                            </div>

                            <div class="col-md-4">
                                <label class="form-label">Initial Stock</label>
                                <input type="number" name="initial_stock" class="form-control" min="0" value="0" required>
                            </div>

                            <div class="col-md-4">
                                <label class="form-label">Month Sales</label>
                                <input type="number" name="month_sales" class="form-control" min="0" value="0" required>
                            </div>

                            <div class="col-md-4">
                                <label class="form-label">Balance Stock</label>
                                <input type="number" name="balance_stock" class="form-control" value="0" readonly>
                            </div>

                            <div class="col-12">
                                <button type="submit" name="save_wholesaler" class="btn btn-primary">
    <i class="fa-solid fa-floppy-disk me-2"></i>
    Save Record
</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <div class="card page-card">
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0 align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th>ID</th>
                                    <th>Product</th>
                                    <th>Month</th>
                                    <th>Initial Stock</th>
                                    <th>Month Sales</th>
                                    <th>Balance Stock</th>
                                    <th>Created</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (count($records) > 0): ?>
                                    <?php foreach ($records as $index => $row): ?>
                                        <tr>
                                            <td><?= $index + 1 ?></td>
                                            <td><?= htmlspecialchars($row['product_name'] ?? 'N/A') ?></td>
                                            <td>
                                                <span class="badge badge-month">
                                                    <?= htmlspecialchars($row['sale_month']) ?>
                                                </span>
                                            </td>
                                            <td><?= (int)$row['initial_stock'] ?></td>
                                            <td><?= (int)$row['month_sales'] ?></td>
                                            <td><?= (int)$row['balance_stock'] ?></td>
                                            <td><?= htmlspecialchars($row['created_at']) ?></td>
                                            <td>
                                                <a href="?delete=<?= (int)$row['id'] ?>"
                                                   class="btn btn-sm btn-danger"
                                                   onclick="return confirm('Delete this record?')">
                                                    Delete
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="8" class="text-center text-muted py-4">No records found</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>

<script>
const initialStockInput = document.querySelector('[name="initial_stock"]');
const monthSalesInput = document.querySelector('[name="month_sales"]');
const balanceStockInput = document.querySelector('[name="balance_stock"]');

function updateBalance() {
    const initialStock = parseInt(initialStockInput.value || '0', 10);
    const monthSales = parseInt(monthSalesInput.value || '0', 10);
    const balance = initialStock - monthSales;
    balanceStockInput.value = balance >= 0 ? balance : 0;
}

if (initialStockInput && monthSalesInput && balanceStockInput) {
    initialStockInput.addEventListener('input', updateBalance);
    monthSalesInput.addEventListener('input', updateBalance);
    updateBalance();
}
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>