<?php
session_start();
if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'admin') {
    header("Location: login.html");
    exit();
}

include 'db_connect.php';

if (!isset($_GET['id'])) {
    echo "Invalid product ID.";
    exit();
}

$product_id = intval($_GET['id']);

// Fetch Product Info
$stmt = $conn->prepare("SELECT name, quantity, buying_price FROM products WHERE id = ?");
$stmt->bind_param("i", $product_id);
$stmt->execute();
$result  = $stmt->get_result();
$product = $result->fetch_assoc();
$stmt->close();

if (!$product) {
    echo "Product not found!";
    exit();
}

// Handle Stock Addition
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $added_quantity   = intval($_POST['quantity']);
    $new_buying_price = floatval($_POST['buying_price']);
    $supplier         = isset($_POST['supplier']) ? trim($_POST['supplier']) : null;

    if ($added_quantity <= 0 || $new_buying_price <= 0) {
        $error = "❌ Quantity and buying price must be greater than zero.";
    } else {

        $conn->begin_transaction();
        try {
            // Insert batch
            $stmt = $conn->prepare("
                INSERT INTO stock_batches (product_id, quantity_added, buying_price, supplier)
                VALUES (?, ?, ?, ?)
            ");
            $stmt->bind_param("iids", $product_id, $added_quantity, $new_buying_price, $supplier);
            $stmt->execute();
            $stmt->close();

            // Compute new averages
            $old_qty       = $product['quantity'];
            $old_avg       = floatval($product['buying_price']);
            $new_total_qty = $old_qty + $added_quantity;
            $new_avg       = round((($old_qty * $old_avg) + ($added_quantity * $new_buying_price)) / $new_total_qty, 2);

            // Update products table
            $stmt2 = $conn->prepare("UPDATE products SET quantity = ?, buying_price = ? WHERE id = ?");
            $stmt2->bind_param("idi", $new_total_qty, $new_avg, $product_id);
            $stmt2->execute();
            $stmt2->close();

            $conn->commit();

            header("Location: manage_products.php?added=1");
            exit();

        } catch (Exception $e) {
            $conn->rollback();
            $error = "❌ Something went wrong: " . $e->getMessage();
        }
    }
}

// page title for head.php
$page_title = "Add Stock";
?>

<!DOCTYPE html>
<html>
<head>
    <title><?= htmlspecialchars($page_title) ?></title>
    <?php include('head.php'); ?> 

    <style>
        /* content to the right of sidebar */
        .content-area {
            margin-left: 500px;
            padding: 40px 40px 60px;
            display: flex;
            justify-content: center; /* center everything horizontally */
        }
        @media (max-width: 768px) {
            .content-area {
                margin-left: 80px;
                padding: 20px;
            }
        }

        /* inner wrapper: wide but still centered */
        .content-inner {
            width: 100%;
            max-width: 1200px;  /* how wide the whole card can get */
        }

        /* page header */
        .page-header {
            text-align: center;
            margin-bottom: 24px;
        }
        .page-title {
            font-size: 22px;
            font-weight: 600;
            color: #f4b400; /* gold works on both dark & light */
        }
        .page-subtitle {
            font-size: 14px;
            color: var(--text-main);
            margin-top: 4px;
        }
        body[data-theme="light"] .page-subtitle {
            color: #4b5563;
        }

        /* main card */
        .form-card {
            background: var(--bg-card);
            padding: 24px 28px 26px;
            border-radius: 14px;
            box-shadow: 0 4px 14px rgba(0,0,0,0.35);
            border: 1px solid #0a4a85;
            width: 100%;           /* use full content-inner width */
            color: var(--text-main);
        }
        body[data-theme="light"] .form-card {
            box-shadow: 0 12px 30px rgba(15,23,42,0.12);
            border-color: rgba(148,163,184,0.55);
        }

        .stock-summary {
            font-size: 13px;
            margin-bottom: 18px;
            text-align: center;
            color: var(--text-main);
        }
        .stock-summary strong {
            color: #f4b400;
        }

        /* error message */
        .error {
            background: rgba(231,76,60,0.18);
            padding: 10px 12px;
            border-left: 5px solid #e74c3c;
            border-radius: 6px;
            margin-bottom: 14px;
            color: #ffb3b3;
            font-size: 13px;
        }

        /* two-column form layout on desktop */
        .form-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(280px, 1fr));
            gap: 18px 22px;
        }
        @media (max-width: 900px) {
            .form-grid {
                grid-template-columns: 1fr;
            }
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        label {
            font-size: 13px;
            font-weight: 500;
            margin-bottom: 4px;
            color: var(--text-main);
        }

        input[type="number"],
        input[type="text"] {
            padding: 9px 10px;
            border-radius: 6px;
            border: 1px solid #0a4a85;
            background: #01356f;
            color: #ffffff;
            font-size: 14px;
        }
        body[data-theme="light"] input[type="number"],
        body[data-theme="light"] input[type="text"] {
            background: #ffffff;
            color: #111827;
            border-color: #cbd5f5;
        }

        input::placeholder {
            color: rgba(230,230,230,0.75);
        }
        body[data-theme="light"] input::placeholder {
            color: #9ca3af;
        }

        input:focus {
            outline: none;
            border-color: #f4b400;
            background: #014b94;
        }
        body[data-theme="light"] input:focus {
            background: #f9fafb;
            border-color: #facc15;
        }

        /* action buttons row */
        .actions-row {
            margin-top: 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            justify-content: flex-end;
        }

        .btn-primary {
            padding: 10px 18px;
            background: #f4b400;
            color: #001f3f;
            border: none;
            border-radius: 6px;
            font-weight: 600;
            cursor: pointer;
            font-size: 14px;
        }

        .btn-primary:hover {
            background: #ffcc00;
        }

        .btn-secondary {
            padding: 10px 16px;
            background: #01356f;
            color: #ffffff;
            border-radius: 6px;
            text-decoration: none;
            font-size: 13px;
            border: 1px solid #0a4a85;
        }
        .btn-secondary:hover {
            background: #014b94;
        }

        body[data-theme="light"] .btn-secondary {
            background: #e5e7eb;
            color: #111827;
            border-color: #cbd5f5;
        }
        body[data-theme="light"] .btn-secondary:hover {
            background: #d1d5db;
        }

        footer {
            background: transparent !important;
        }
    </style>
</head>

<body>

<div class="wrapper">
    <?php include("sidebar.php"); ?>

    <div class="content-area">
        <div class="content-inner">

            <div class="page-header">
                <div class="page-title">Add Stock</div>
                <div class="page-subtitle">
                    <?= htmlspecialchars($product['name']) ?>
                </div>
            </div>

            <div class="form-card">

                <div class="stock-summary">
                    <strong>Current stock:</strong> <?= $product['quantity'] ?>
                    &nbsp; | &nbsp;
                    <strong>Average buying price:</strong> KES <?= number_format($product['buying_price'], 2) ?>
                </div>

                <?php if (isset($error)): ?>
                    <div class="error"><?= $error ?></div>
                <?php endif; ?>

                <form method="post">
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Quantity to add</label>
                            <input type="number" name="quantity" min="1" required>
                        </div>

                        <div class="form-group">
                            <label>Buying price (KES per unit)</label>
                            <input type="number" name="buying_price" step="0.01" required>
                        </div>

                        <div class="form-group" style="grid-column: 1 / -1;">
                            <label>Supplier (optional)</label>
                            <input type="text" name="supplier" placeholder="Supplier name">
                        </div>
                    </div>

                    <div class="actions-row">
                        <button type="submit" class="btn-primary">Save stock update</button>
                        <a href="batch_list.php" class="btn-secondary">View stock batches</a>
                    </div>
                </form>

            </div>

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

<?php include 'footer.php'; ?>
</body>
</html>
