<?php
// Output buffering start - Redirection ke liye lazmi hai
ob_start(); 

$sidebar_path = "/home/tameeralmadina/public_html/TAM/sidebar";
if (file_exists($sidebar_path)) {
    include $sidebar_path;
} elseif (file_exists($sidebar_path . ".php")) {
    include $sidebar_path . ".php";
}

include "db.php";

$error = "";

// ---- Fetch all products for dropdown ----
$products = [];
$prod_result = $conn->query("SELECT product_id, product_name, stock_quantity FROM products ORDER BY product_name ASC");
if ($prod_result) {
    while ($row = $prod_result->fetch_assoc()) {
        $products[] = $row;
    }
}

if (isset($_POST['submit'])) {

    $product_id = intval($_POST['product_id']);
    $type = ($_POST['type'] === 'out') ? 'out' : 'in';
    $quantity = intval($_POST['quantity']);
    $unit_price = ($_POST['unit_price'] !== '') ? floatval($_POST['unit_price']) : null;
    $currency = !empty($_POST['currency']) ? $_POST['currency'] : 'PKR'; // Rs (PKR) ya OMR
    $description = trim($_POST['description']);
    $date = !empty($_POST['date']) ? $_POST['date'] : date('Y-m-d');
    $time = !empty($_POST['time']) ? $_POST['time'] : date('H:i');

    if ($product_id <= 0 || $quantity <= 0) {
        $error = "Please select a product and enter a valid quantity.";
    } else {

        // Get current stock + product name
        $check = $conn->prepare("SELECT product_name, stock_quantity FROM products WHERE product_id = ?");
        $check->bind_param("i", $product_id);
        $check->execute();
        $check_result = $check->get_result();
        $product_row = $check_result->fetch_assoc();
        $check->close();

        if (!$product_row) {
            $error = "Selected product not found.";
        } elseif ($type === 'out' && $quantity > $product_row['stock_quantity']) {
            $error = "Cannot remove " . $quantity . " units — only " . $product_row['stock_quantity'] . " in stock.";
        } else {

            $conn->begin_transaction();

            try {
                // 1) Insert adjustment record
                $stmt = $conn->prepare("INSERT INTO inventory (product_id, type, name, quantity, unit_price, currency, description, date, time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->bind_param("issidssss", $product_id, $type, $product_row['product_name'], $quantity, $unit_price, $currency, $description, $date, $time);
                $stmt->execute();
                $stmt->close();

                // 2) Update product stock
                if ($type === 'in') {
                    $update = $conn->prepare("UPDATE products SET stock_quantity = stock_quantity + ? WHERE product_id = ?");
                } else {
                    $update = $conn->prepare("UPDATE products SET stock_quantity = stock_quantity - ? WHERE product_id = ?");
                }
                $update->bind_param("ii", $quantity, $product_id);
                $update->execute();
                $update->close();

                $conn->commit();

                // Safe Redirect - buffer clear karke phir header bhejna
                if (ob_get_length()) {
                    ob_end_clean();
                }

                if (!headers_sent()) {
                    header("Location: inventory_view.php");
                    exit();
                } else {
                    echo "<script>window.location.href='inventory_view.php';</script>";
                    exit();
                }

            } catch (Exception $e) {
                $conn->rollback();
                $error = "Error saving adjustment: " . $e->getMessage();
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stock Adjustment - Tameer Al Madina</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<style>
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    background: #F4F6F9;
    font-family: 'Poppins', sans-serif;
    min-height: 100vh;
}

.main-layout {
    display: flex;
    width: 100%;
    min-height: 100vh;
    position: relative;
}

aside, .sidebar, [class*="sidebar"] {
    width: 260px;
    min-width: 260px;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1000;
    transition: all 0.3s ease;
}

.content-wrapper {
    flex: 1;
    margin-left: 260px;
    display: flex;
    flex-direction: column;
    background: #F4F6F9;
    min-width: 0;
    width: calc(100% - 260px);
    transition: all 0.3s ease;
}

.top-navbar {
    height: 60px;
    background: #FFFFFF;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 30px;
    border-bottom: 1px solid #EAEAEA;
}

.navbar-left-flex {
    display: flex;
    align-items: center;
    gap: 15px;
}

.mobile-menu-toggle {
    display: none;
    font-size: 20px;
    color: #0A192F;
    cursor: pointer;
    background: #F4F6F9;
    width: 38px;
    height: 38px;
    align-items: center;
    justify-content: center;
    border-radius: 6px;
    border: 1px solid #E2E8F0;
}

.search-container {
    position: relative;
    width: 300px;
}

.search-container input {
    width: 100%;
    padding: 8px 15px 8px 40px;
    background: #F8F9FA;
    border: 1px solid #E2E8F0;
    border-radius: 8px;
    font-size: 13px;
    outline: none;
}

.search-container i {
    position: absolute;
    left: 15px;
    top: 50%;
    transform: translateY(-50%);
    color: #A0AEC0;
}

.user-profile {
    display: flex;
    align-items: center;
    gap: 20px;
}

.profile-info {
    display: flex;
    align-items: center;
    gap: 10px;
}

.profile-info i.profile-icon {
    font-size: 26px;
    color: #4A5568;
    background: #F4F6F9;
    width: 36px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    border: 1px solid #E2E8F0;
}

.profile-text h4 {
    font-size: 13px;
    color: #1A202C;
    font-weight: 600;
}

.profile-text p {
    font-size: 11px;
    color: #718096;
}

.page-container {
    padding: 20px 30px;
    flex: 1;
    display: flex;
    flex-direction: column;
}

.form-card {
    background: #FFFFFF;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
    overflow: hidden;
    width: 100%;
    display: flex;
    flex-direction: column;
    flex: 1;
}

form {
    display: flex;
    flex-direction: column;
    flex: 1;
}

.form-banner {
    background: linear-gradient(135deg, #0A192F 0%, #172A45 100%);
    padding: 15px 30px;
    color: #FFFFFF;
    border-bottom: 4px solid #28A745;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.banner-left {
    display: flex;
    align-items: center;
    gap: 12px;
}

.banner-icon {
    background: rgba(255, 255, 255, 0.1);
    width: 38px;
    height: 38px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 6px;
    font-size: 16px;
}

.banner-text h2 {
    font-size: 18px;
    font-weight: 600;
}

.banner-text p {
    font-size: 11px;
    color: #A0AEC0;
}

.banner-right-text {
    font-size: 18px;
    font-weight: 700;
    color: rgba(255, 255, 255, 0.15);
}

.section-header {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 18px 30px 10px 30px;
    font-size: 14px;
    font-weight: 600;
    color: #0A192F;
}

.section-header i {
    color: #28A745;
    font-size: 16px;
}

.form-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr); 
    gap: 15px 25px;
    padding: 0 30px;
}

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

.form-group label {
    font-size: 12px;
    font-weight: 500;
    color: #2D3748;
    margin-bottom: 6px;
}

.required {
    color: #E53E3E;
    margin-left: 3px;
}

.input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
}

.input-wrapper i {
    position: absolute;
    left: 15px;
    color: #A0AEC0;
    font-size: 13px;
    z-index: 2;
}

.input-wrapper input,
.input-wrapper select {
    width: 100%;
    height: 38px;
    border: 1px solid #E2E8F0;
    border-radius: 6px;
    padding: 5px 15px 5px 40px;
    font-size: 13px;
    color: #4A5568;
    background: #FFFFFF;
    outline: none;
}

.input-wrapper textarea {
    width: 100%;
    height: 38px; 
    border: 1px solid #E2E8F0;
    border-radius: 6px;
    padding: 8px 15px 8px 40px;
    font-size: 13px;
    color: #4A5568;
    resize: none;
}

.input-wrapper input:focus,
.input-wrapper select:focus,
.input-wrapper textarea:focus {
    border-color: #28A745;
    box-shadow: 0 0 0 2px rgba(40, 167, 69, 0.1);
    outline: none;
}

.full-width {
    grid-column: span 3;
}

.stock-hint {
    font-size: 11px;
    color: #718096;
    margin-top: 4px;
}

.type-toggle {
    display: flex;
    gap: 10px;
}

.type-btn {
    flex: 1;
    height: 38px;
    border: 1px solid #E2E8F0;
    border-radius: 6px;
    background: #FFFFFF;
    font-size: 13px;
    font-weight: 500;
    color: #4A5568;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.type-btn.active-in {
    background: #E6FFFA;
    border-color: #28A745;
    color: #1A7F4E;
}

.type-btn.active-out {
    background: #FFF5F5;
    border-color: #E53E3E;
    color: #C53030;
}

.alert-container {
    padding: 15px 30px 0 30px;
}

.alert {
    padding: 10px 15px;
    border-radius: 6px;
    font-size: 13px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.alert-error { background: #FFF5F5; border: 1px solid #FED7D7; color: #E53E3E; }

.form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 20px 30px 25px 30px;
    margin-top: auto; 
    border-top: 1px solid #F0F2F5;
}

.btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 8px 22px;
    border: none;
    border-radius: 6px;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
}

.btn-cancel { background: #EDF2F7; color: #4A5568; }
.btn-submit { background: #28A745; color: #FFFFFF; }

.sidebar-overlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.4);
    z-index: 998;
}

@media (min-width: 992px) {
    body { overflow: hidden; }
    .page-container { height: calc(100vh - 60px); }
}

@media (max-width: 1024px) and (min-width: 769px) {
    aside, .sidebar, [class*="sidebar"] { width: 240px; min-width: 240px; }
    .content-wrapper { margin-left: 240px; width: calc(100% - 240px); }
    .form-grid { grid-template-columns: repeat(2, 1fr); }
    .full-width { grid-column: span 2; }
}

@media (max-width: 768px) {
    body { overflow-y: auto !important; }
    .mobile-menu-toggle { display: inline-flex; }
    aside, .sidebar, [class*="sidebar"] { left: -260px !important; }
    aside.active, .sidebar.active, [class*="sidebar"].active { left: 0 !important; }
    .content-wrapper { margin-left: 0 !important; width: 100% !important; }
    .top-navbar { padding: 0 15px; }
    .search-container { width: 140px; }
    .page-container { padding: 10px; }
    .form-banner { padding: 12px 15px; }
    .banner-right-text { display: none; }
    .section-header { padding: 15px 15px 8px 15px; }
    .form-grid { grid-template-columns: 1fr !important; padding: 0 15px; gap: 12px; }
    .full-width { grid-column: span 1; }
    .form-actions { padding: 15px; justify-content: space-between; }
    .btn { flex: 1; justify-content: center; }
}
</style>
</head>
<body>

<div class="sidebar-overlay" id="sidebarOverlay" onclick="toggleMobileSidebar()"></div>

<div class="main-layout">
    
    <?php 
    if (file_exists($sidebar_path)) {
        include $sidebar_path;
    } elseif (file_exists($sidebar_path . ".php")) {
        include $sidebar_path . ".php";
    }
    ?>

    <div class="content-wrapper">
        
        <div class="top-navbar">
            <div class="navbar-left-flex">
                <div class="mobile-menu-toggle" onclick="toggleMobileSidebar()">
                    <i class="fa-solid fa-bars"></i>
                </div>
                <div class="search-container">
                    <i class="fa-solid fa-magnifying-glass"></i>
                    <input type="text" placeholder="Search here...">
                </div>
            </div>
            
            <div class="user-profile">
                <div class="profile-info">
                    <i class="fa-solid fa-circle-user profile-icon"></i>
                    <div class="profile-text">
                        <h4>Admin</h4>
                        <p>Administrator</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="page-container">
            <div class="form-card">
                
                <div class="form-banner">
                    <div class="banner-left">
                        <div class="banner-icon">
                            <i class="fa-solid fa-boxes-stacked"></i>
                        </div>
                        <div class="banner-text">
                            <h2>Stock Adjustment</h2>
                            <p>Stock in or stock out an existing product, or add a new one</p>
                        </div>
                    </div>
                    <div class="banner-right-text">Tameer Al Madina</div>
                </div>

                <?php if(!empty($error)): ?>
                    <div class="alert-container">
                        <div class="alert alert-error">
                            <i class="fa-solid fa-triangle-exclamation"></i> <?= htmlspecialchars($error) ?>
                        </div>
                    </div>
                <?php endif; ?>

                <form method="POST" id="adjustmentForm">
                    
                    <div>
                        <div class="section-header">
                            <i class="fa-solid fa-box"></i> Adjustment Details
                        </div>

                        <div class="form-grid">

                            <div class="form-group full-width">
                                <label>Product<span class="required">*</span></label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-tags"></i>
                                    <select name="product_id" id="productSelect" required onchange="handleProductChange(this)">
                                        <option value="">-- Select Product --</option>
                                        <?php foreach ($products as $p): ?>
                                            <option value="<?= $p['product_id'] ?>" data-stock="<?= $p['stock_quantity'] ?>">
                                                <?= htmlspecialchars($p['product_name']) ?> (Current stock: <?= $p['stock_quantity'] ?>)
                                            </option>
                                        <?php endforeach; ?>
                                        <option value="new">+ Add New Product</option>
                                    </select>
                                </div>
                                <div class="stock-hint" id="stockHint"></div>
                            </div>

                            <div class="form-group full-width">
                                <label>Adjustment Type<span class="required">*</span></label>
                                <input type="hidden" name="type" id="typeInput" value="in">
                                <div class="type-toggle">
                                    <button type="button" class="type-btn active-in" id="btnIn" onclick="setType('in')">
                                        <i class="fa-solid fa-arrow-down"></i> Stock In
                                    </button>
                                    <button type="button" class="type-btn" id="btnOut" onclick="setType('out')">
                                        <i class="fa-solid fa-arrow-up"></i> Stock Out
                                    </button>
                                </div>
                            </div>

                            <div class="form-group">
                                <label>Date<span class="required">*</span></label>
                                <div class="input-wrapper">
                                    <i class="fa-regular fa-calendar"></i>
                                    <input type="date" name="date" required value="<?php echo date('Y-m-d'); ?>">
                                </div>
                            </div>

                            <div class="form-group">
                                <label>Time<span class="required">*</span></label>
                                <div class="input-wrapper">
                                    <i class="fa-regular fa-clock"></i>
                                    <input type="time" name="time" required value="<?php echo date('H:i'); ?>">
                                </div>
                            </div>

                            <div class="form-group">
                                <label>Quantity<span class="required">*</span></label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-cubes"></i>
                                    <input type="number" step="1" min="1" name="quantity" placeholder="0" required>
                                </div>
                            </div>

                            <div class="form-group">
                                <label>Unit Price</label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-dollar-sign" id="unitPriceIcon"></i>
                                    <input type="number" step="0.01" min="0" name="unit_price" id="unitPriceInput" placeholder="0.00">
                                </div>
                            </div>

                            <div class="form-group">
                                <label>Currency</label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-money-bill-transfer"></i>
                                    <select name="currency" id="currencySelect" onchange="updateUnitPriceFormat()">
                                        <option value="PKR" selected>PKR - Rs (Pakistani Rupee)</option>
                                        <option value="OMR">OMR (Omani Rial)</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group full-width">
                                <label>Reason / Description</label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-align-left"></i>
                                    <textarea name="description" placeholder="e.g. Damaged stock, manual correction, wastage"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-actions">
                        <button type="button" onclick="window.history.back();" class="btn btn-cancel">
                            <i class="fa-solid fa-xmark"></i> Cancel
                        </button>
                        <button type="submit" name="submit" class="btn btn-submit">
                            <i class="fa-regular fa-floppy-disk"></i> Save Adjustment
                        </button>
                    </div>

                </form>

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

<script>
function toggleMobileSidebar() {
    const sidebarElements = document.querySelectorAll('aside, .sidebar, [class*="sidebar"]');
    const overlay = document.getElementById('sidebarOverlay');
    
    sidebarElements.forEach(sidebar => {
        sidebar.classList.toggle('active');
    });
    
    if(sidebarElements[0] && sidebarElements[0].classList.contains('active')) {
        overlay.style.display = 'block';
    } else {
        overlay.style.display = 'none';
    }
}

function setType(type) {
    document.getElementById('typeInput').value = type;
    const btnIn = document.getElementById('btnIn');
    const btnOut = document.getElementById('btnOut');
    if (type === 'in') {
        btnIn.classList.add('active-in');
        btnOut.classList.remove('active-out');
    } else {
        btnOut.classList.add('active-out');
        btnIn.classList.remove('active-in');
    }
}

function handleProductChange(select) {
    if (select.value === 'new') {
        window.open('add_product.php', '_blank');
        select.value = ''; // reset so form doesn't submit "new" as product_id
        document.getElementById('stockHint').textContent = '';
        return;
    }
    const selectedOption = select.options[select.selectedIndex];
    const stock = selectedOption.getAttribute('data-stock');
    const hint = document.getElementById('stockHint');
    if (stock !== null && select.value !== '') {
        hint.textContent = 'Current stock in system: ' + stock + ' units';
    } else {
        hint.textContent = '';
    }
}

function updateUnitPriceFormat() {
    var currencySelect = document.getElementById("currencySelect");
    var unitPriceInput = document.getElementById("unitPriceInput");
    var unitPriceIcon = document.getElementById("unitPriceIcon");

    if (currencySelect.value === "OMR") {
        // OMR mein 3 decimal places hote hain (e.g. 0.000)
        unitPriceInput.step = "0.001";
        unitPriceInput.placeholder = "0.000";

        unitPriceIcon.classList.remove("fa-dollar-sign");
        unitPriceIcon.classList.add("fa-coins");

        if (unitPriceInput.value !== "") {
            unitPriceInput.value = parseFloat(unitPriceInput.value).toFixed(3);
        }
    } else {
        // PKR (Rs) mein 2 decimal places
        unitPriceInput.step = "0.01";
        unitPriceInput.placeholder = "0.00";

        unitPriceIcon.classList.remove("fa-coins");
        unitPriceIcon.classList.add("fa-dollar-sign");

        if (unitPriceInput.value !== "") {
            unitPriceInput.value = parseFloat(unitPriceInput.value).toFixed(2);
        }
    }
}
</script>

</body>
</html>