<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

session_start();
require_once("../config/config.php");

if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['admin', 'store manager'])) {
    header("Location: ../login.php");
    exit();
}

$success = "";
$error = "";

// Get Next SKU
function getNextSKU(mysqli $conn): string {
    $sql = "SELECT sku FROM inventory_master ORDER BY id DESC LIMIT 1";
    $res = $conn->query($sql);
    $next = 1;
    if ($res && $row = $res->fetch_assoc()) {
        $next = (int)substr($row['sku'], 3) + 1;
    }
    return sprintf("IN-%03d", $next);
}

$nextSKU = getNextSKU($conn);

// Fetch Master Data
$vendors    = $conn->query("SELECT id, vendor_name FROM vendor_master ORDER BY vendor_name ASC")->fetch_all(MYSQLI_ASSOC);
$warehouses = $conn->query("SELECT id, warehouse_name, location FROM warehouse_master WHERE status = 'Active' ORDER BY warehouse_name ASC")->fetch_all(MYSQLI_ASSOC);
$projects   = $conn->query("SELECT id, project_name FROM project_master ORDER BY project_name ASC")->fetch_all(MYSQLI_ASSOC);
$categories = $conn->query("SELECT id, category AS category_name FROM category_tbl ORDER BY category ASC")->fetch_all(MYSQLI_ASSOC);
$uoms       = $conn->query("SELECT id, uom_name FROM uom_tbl ORDER BY uom_name ASC")->fetch_all(MYSQLI_ASSOC);

// ====================== AJAX: Add Category / UOM ======================
if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    $response = ['success' => false, 'message' => ''];
    $name = trim($_POST['name'] ?? '');
    if ($name) {
        if ($_POST['action'] === 'add_category') {
            $stmt = $conn->prepare("INSERT INTO category_tbl (category) VALUES (?)");
            $stmt->bind_param("s", $name);
            if ($stmt->execute()) $response = ['success' => true, 'id' => $conn->insert_id, 'name' => $name];
        }
        if ($_POST['action'] === 'add_uom') {
            $stmt = $conn->prepare("INSERT INTO uom_tbl (uom_name) VALUES (?)");
            $stmt->bind_param("s", $name);
            if ($stmt->execute()) $response = ['success' => true, 'id' => $conn->insert_id, 'name' => $name];
        }
    }
    echo json_encode($response);
    exit;
}

// ====================== FORM SUBMISSION ======================
if ($_SERVER["REQUEST_METHOD"] === "POST" && !isset($_POST['action'])) {
    $warehouse_id = (int)($_POST['warehouse_id'] ?? 0);
    $project_id   = (int)($_POST['project_id'] ?? 0);
    $invoice_id   = trim($_POST['invoice_id'] ?? '');
    $items        = $_POST['items'] ?? [];

    if ($warehouse_id <= 0 || $project_id <= 0) {
        $error = "Please select warehouse and project.";
    } elseif (empty($items)) {
        $error = "Please add at least one material.";
    } else {
        mysqli_begin_transaction($conn);
        try {
            $stmt = $conn->prepare("INSERT INTO purchase_entries (warehouse_id, project_id, invoice_id) VALUES (?, ?, ?)");
            $stmt->bind_param("iis", $warehouse_id, $project_id, $invoice_id);
            $stmt->execute();
            $purchase_id = $conn->insert_id;

            $basic_total = 0;
            $discount_total = 0;

            $item_stmt = $conn->prepare("INSERT INTO purchase_entry_items 
                (purchase_entry_id, serial_no, sku, name, model_no, hsn_sac, category, supplier_vendor, uom,
                 quantity, rate, amount, discount, cgst, sgst, igst, description)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

            foreach ($items as $item) {
                $serial_no      = (int)($item['serial_no'] ?? 0);
                $name           = trim($item['name'] ?? '');
                $model_no       = trim($item['model_no'] ?? '');
                $hsn_sac        = trim($item['hsn_sac'] ?? '');
                $category       = $item['category'] ?? '';
                $supplier_vendor = (int)($item['supplier_vendor'] ?? 0);
                $uom            = $item['uom'] ?? '';
                $quantity       = floatval($item['quantity'] ?? 0);
                $rate           = floatval($item['rate'] ?? 0);
                $discount       = floatval($item['discount'] ?? 0);
                $amount         = floatval($item['amount'] ?? ($quantity * $rate));
                $cgst           = floatval($item['cgst'] ?? 0);
                $sgst           = floatval($item['sgst'] ?? 0);
                $igst           = floatval($item['igst'] ?? 0);
                $description    = trim($item['description'] ?? '');
                $sku            = trim($item['sku'] ?? '');

                // FIXED: Collect all serial numbers properly
                $serial_numbers = [];
                if (isset($item['serial_number']) && is_array($item['serial_number'])) {
                    $serial_numbers = array_filter(array_map('trim', $item['serial_number']));
                }

                if (empty($name) || $quantity <= 0) continue;

                // Check if material exists
                $check = $conn->prepare("SELECT id, sku FROM inventory_master WHERE name = ? LIMIT 1");
                $check->bind_param("s", $name);
                $check->execute();
                $result = $check->get_result();

                if ($result->num_rows === 0) {
                    // NEW MATERIAL
                    $new_sku = getNextSKU($conn);
                    $insert = $conn->prepare("INSERT INTO inventory_master 
                        (sku, name, description, hsn_sac, category, warehouse_id, model_no, supplier_vendor, uom, current_stock) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $insert->bind_param("sssssisssd", $new_sku, $name, $description, $hsn_sac, $category, $warehouse_id, $model_no, $supplier_vendor, $uom, $quantity);
                    $insert->execute();
                    $inventory_id = $conn->insert_id;
                    $sku = $new_sku;
                } else {
                    // EXISTING MATERIAL - Update
                    $existing = $result->fetch_assoc();
                    $inventory_id = $existing['id'];
                    $sku = $existing['sku'];

                    $update = $conn->prepare("UPDATE inventory_master SET 
                        current_stock = current_stock + ?,
                        description = ?, hsn_sac = ?, model_no = ?, category = ?, 
                        uom = ?, supplier_vendor = ? WHERE id = ?");
                    $update->bind_param("dssssssi", $quantity, $description, $hsn_sac, $model_no, $category, $uom, $supplier_vendor, $inventory_id);
                    $update->execute();
                }

                // Insert Purchase Item
                $item_stmt->bind_param("iisssssisddddddds",
                    $purchase_id, $serial_no, $sku, $name, $model_no, $hsn_sac, $category,
                    $supplier_vendor, $uom, $quantity, $rate, $amount, $discount,
                    $cgst, $sgst, $igst, $description);
                $item_stmt->execute();
                $purchase_item_id = $conn->insert_id;

                // === INSERT SERIAL NUMBERS (Fixed & Working) ===
                if (!empty($serial_numbers)) {
                    // Into inventory_serials
                    $ser_stmt = $conn->prepare("INSERT INTO inventory_serials (inventory_id, serial_number, status, created_at) VALUES (?, ?, 'In Stock', NOW())");
                    foreach ($serial_numbers as $sn) {
                        if (!empty($sn)) {
                            $ser_stmt->bind_param("is", $inventory_id, $sn);
                            $ser_stmt->execute();
                        }
                    }

                    // Into purchase_item_serials
                    $p_ser_stmt = $conn->prepare("INSERT INTO purchase_item_serials (purchase_entry_item_id, serial_number, created_at) VALUES (?, ?, NOW())");
                    foreach ($serial_numbers as $sn) {
                        if (!empty($sn)) {
                            $p_ser_stmt->bind_param("is", $purchase_item_id, $sn);
                            $p_ser_stmt->execute();
                        }
                    }
                }

                $basic_total += $amount;
                $discount_total += $discount;
            }

            // Update Totals
            $taxable = $basic_total - $discount_total;
            $gst_total = $taxable * 0.18;
            $grand_total = $taxable + $gst_total;

            $upd = $conn->prepare("UPDATE purchase_entries SET total_basic=?, total_discount=?, total_gst=?, grand_total=? WHERE id=?");
            $upd->bind_param("ddddi", $basic_total, $discount_total, $gst_total, $grand_total, $purchase_id);
            $upd->execute();

            mysqli_commit($conn);
            $success = "✅ Purchase saved successfully! New serial numbers added to both tables.";

        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error = "Error: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Purchase Entry</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root { --primary: #a855f7; --glass: rgba(255,255,255,0.10); --glass-border: rgba(255,255,255,0.20); }
        * { margin:0; padding:0; box-sizing:border-box; }
        body { font-family: 'Inter', system-ui, sans-serif; background: linear-gradient(135deg, rgba(0,0,0,0.78), rgba(0,0,0,0.92)), url('../background.jpeg') center/cover fixed; color: #f1f5f9; min-height: 100vh; padding: 20px; }
        .glass-container { max-width: 1350px; margin: auto; background: var(--glass); backdrop-filter: blur(24px); border-radius: 32px; border: 1px solid var(--glass-border); box-shadow: 0 25px 80px rgba(0,0,0,0.65); overflow: hidden; }
        .header { background: linear-gradient(90deg, rgba(168,85,247,0.35), rgba(147,51,234,0.25)); padding: 50px 40px; text-align:center; }
        .header h1 { font-size: clamp(32px, 5.5vw, 46px); font-weight:700; }
        .form-area { padding: 45px 40px; }
        .section, .item-row { background: rgba(255,255,255,0.07); border: 1px solid rgba(255,255,255,0.2); border-radius: 20px; padding: 28px; margin-bottom: 25px; position: relative; }
        .remove-btn { position: absolute; top:18px; right:18px; background: rgba(239,68,68,0.8); color:white; border:none; width:38px; height:38px; border-radius:50%; font-size:24px; cursor:pointer; }
        .form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 18px; }
        label { display:block; margin-bottom:8px; font-weight:600; }
        .required { color:#f87171; }
        input, select, textarea { width:100%; padding:13px 16px; background:rgba(255,255,255,0.09); border:1px solid rgba(255,255,255,0.25); border-radius:12px; color:white; font-size:15px; }
        input:focus, select:focus { border-color:var(--primary); box-shadow:0 0 0 3px rgba(168,85,247,0.25); }
        .suggestions { position:absolute; z-index:1000; background:#1f2937; border:1px solid #a855f7; border-radius:12px; max-height:280px; overflow-y:auto; width:100%; margin-top:4px; box-shadow:0 10px 30px rgba(0,0,0,0.6); }
        .suggestion-item { padding:12px 16px; cursor:pointer; border-bottom:1px solid rgba(255,255,255,0.1); }
        .suggestion-item:hover { background:rgba(168,85,247,0.3); }
        .existing-serials-info { margin-top:12px; padding:12px; background:rgba(168,85,247,0.15); border:1px solid #c084fc; border-radius:12px; font-size:0.95rem; color:#e0e7ff; }
        .add-row-btn, .submit-btn { width:100%; padding:18px; border-radius:16px; font-weight:700; font-size:17px; cursor:pointer; margin:25px 0; }
        .add-row-btn { background:rgba(255,255,255,0.06); border:2px dashed #c084fc; color:white; }
        .submit-btn { background:linear-gradient(135deg, var(--primary), #c084fc); color:white; border:none; }
        .message { padding:16px 24px; border-radius:16px; margin-bottom:25px; font-weight:600; }
        .success { background:rgba(34,197,94,0.25); border:1px solid #4ade80; color:#86efac; }
        .error { background:rgba(239,68,68,0.25); border:1px solid #f87171; color:#fca5a5; }
    </style>
</head>
<body>
<?php include '../config/header.php'; ?>

<div class="glass-container">
    <div class="header">
        <h1><i class="fas fa-cart-plus"></i> Add Purchase Entry</h1>
        <p>Record purchase with live inventory + serial number sync</p>
    </div>

    <div class="form-area">
        <?php if ($success): ?><div class="message success"><?= $success ?></div><?php endif; ?>
        <?php if ($error): ?><div class="message error"><?= htmlspecialchars($error) ?></div><?php endif; ?>

        <form action="" method="POST" id="purchaseForm">
            <div class="section">
                <div class="form-grid">
                    <div><label>Warehouse <span class="required">*</span></label>
                        <select name="warehouse_id" required>
                            <option value="">-- Select Warehouse --</option>
                            <?php foreach ($warehouses as $w): ?>
                                <option value="<?= $w['id'] ?>"><?= htmlspecialchars($w['warehouse_name']) ?> — <?= htmlspecialchars($w['location']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div><label>Project <span class="required">*</span></label>
                        <select name="project_id" required>
                            <option value="">-- Select Project --</option>
                            <?php foreach ($projects as $p): ?>
                                <option value="<?= $p['id'] ?>"><?= htmlspecialchars($p['project_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div><label>Invoice Number</label>
                        <input type="text" name="invoice_id" placeholder="INV-XXXXXX">
                    </div>
                </div>
            </div>

            <div id="itemsContainer"></div>

            <button type="button" class="add-row-btn" onclick="addNewRow()">
                <i class="fas fa-plus-circle"></i> Add Another Material
            </button>

            <button type="submit" class="submit-btn">
                <i class="fas fa-save"></i> Save Purchase & Update Stock
            </button>
        </form>
    </div>
</div>

<!-- Modal -->
<div id="addModal" style="display:none;position:fixed;z-index:2000;left:0;top:0;width:100%;height:100%;background:rgba(0,0,0,0.85);align-items:center;justify-content:center;">
    <div style="background:#1f2937;color:white;padding:32px;border-radius:20px;width:90%;max-width:440px;">
        <div id="modalTitle" style="margin-bottom:20px;font-size:18px;font-weight:600;">Add New</div>
        <input type="text" id="modalName" placeholder="Enter Name" style="width:100%;padding:14px;border-radius:12px;background:#374151;border:none;color:white;margin-bottom:25px;">
        <div style="display:flex;gap:12px;">
            <button onclick="closeModal()" style="flex:1;padding:14px;background:#4b5563;color:white;border:none;border-radius:12px;">Cancel</button>
            <button onclick="saveModal()" style="flex:1;padding:14px;background:#a855f7;color:white;border:none;border-radius:12px;">Save</button>
        </div>
    </div>
</div>

<script>
let rowCount = 0;
const baseSKU = "<?= $nextSKU ?>";
const vendors = <?= json_encode($vendors) ?>;
const categories = <?= json_encode($categories) ?>;
const uomsList = <?= json_encode($uoms) ?>;

function escapeHtml(str) {
    return str ? str.replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[m]) : '';
}

function addNewRow() {
    rowCount++;
    let vendorOptions = '<option value="">-- Choose Vendor --</option>';
    vendors.forEach(v => vendorOptions += `<option value="${v.id}">${escapeHtml(v.vendor_name)}</option>`);

    let catOptions = '<option value="">Select Category</option>';
    categories.forEach(c => catOptions += `<option value="${c.id}">${escapeHtml(c.category_name)}</option>`);

    let uomOptions = '<option value="">Select UOM</option>';
    uomsList.forEach(u => uomOptions += `<option value="${u.id}">${escapeHtml(u.uom_name)}</option>`);

    const html = `
        <div class="item-row" id="row-${rowCount}">
            <button type="button" class="remove-btn" onclick="removeRow(${rowCount})">×</button>
            <div class="form-grid">
                <div><label>Sr. No</label><input type="text" name="items[${rowCount}][serial_no]" value="${rowCount}" readonly></div>
                <div><label>Category</label><select name="items[${rowCount}][category]" class="category-select">${catOptions}</select><div class="add-option-btn" onclick="openAddModal(this, 'category')">+ Add new category</div></div>
                <div style="position:relative;"><label>Material Name <span class="required">*</span></label><input type="text" name="items[${rowCount}][name]" required placeholder="Type to search..." onkeyup="searchMaterial(this)"></div>
                <div><label>SKU</label><input type="text" name="items[${rowCount}][sku]" readonly></div>
                <div><label>Model No</label><input type="text" name="items[${rowCount}][model_no]"></div>
                <div><label>HSN/SAC</label><input type="text" name="items[${rowCount}][hsn_sac]"></div>
                <div><label>Supplier / Vendor</label><select name="items[${rowCount}][supplier_vendor]">${vendorOptions}</select></div>
                <div><label>UOM</label><select name="items[${rowCount}][uom]" class="uom-select">${uomOptions}</select><div class="add-option-btn" onclick="openAddModal(this, 'uom')">+ Add new UOM</div></div>
                <div><label>Quantity</label><input type="number" step="0.001" name="items[${rowCount}][quantity]" oninput="calculateRow(this)"></div>
                <div><label>Rate (₹)</label><input type="number" step="0.01" name="items[${rowCount}][rate]" oninput="calculateRow(this)"></div>
                <div><label>Discount (₹)</label><input type="number" step="0.01" name="items[${rowCount}][discount]" value="0" oninput="calculateRow(this)"></div>
                <div><label>Amount (₹)</label><input type="number" step="0.01" name="items[${rowCount}][amount]" readonly></div>
                <div class="full-width">
                    <label>Serial Numbers (One per line)</label>
                    <div class="serial-container" id="serial-container-${rowCount}">
                        <div class="serial-input"><input type="text" name="items[${rowCount}][serial_number][]" placeholder="Enter new serial number"></div>
                    </div>
                    <div onclick="addSerialField(${rowCount})" style="color:#a855f7;cursor:pointer;margin-top:8px;">+ Add another serial</div>
                </div>
                <div class="full-width"><label>Description</label><textarea name="items[${rowCount}][description]" rows="2"></textarea></div>
            </div>
        </div>`;
    document.getElementById('itemsContainer').insertAdjacentHTML('beforeend', html);
}

function searchMaterial(input) {
    const query = input.value.trim();
    const row = input.closest('.item-row');
    let dropdown = row.querySelector('.suggestions');
    if (!dropdown) {
        dropdown = document.createElement('div');
        dropdown.className = 'suggestions';
        input.parentElement.appendChild(dropdown);
    }
    if (query.length < 2) {
        dropdown.style.display = 'none';
        return;
    }
    fetch(`search_material.php?name=${encodeURIComponent(query)}`)
        .then(r => r.json())
        .then(data => {
            dropdown.innerHTML = '';
            if (data.length === 0) {
                dropdown.innerHTML = `<div class="suggestion-item" style="color:#888;">No match. New material will be created.</div>`;
            } else {
                data.forEach(item => {
                    const div = document.createElement('div');
                    div.className = 'suggestion-item';
                    div.innerHTML = `<strong>${escapeHtml(item.name)}</strong> <small>(${item.sku}) - Stock: ${item.current_stock}</small>`;
                    div.onclick = () => selectMaterial(row, item);
                    dropdown.appendChild(div);
                });
            }
            dropdown.style.display = 'block';
        });
}

function selectMaterial(row, material) {
    row.querySelector('[name*="name"]').value = material.name || '';
    row.querySelector('[name*="sku"]').value = material.sku || '';
    row.querySelector('[name*="hsn_sac"]').value = material.hsn_sac || '';
    row.querySelector('[name*="category"]').value = material.category || '';
    row.querySelector('[name*="uom"]').value = material.uom || '';
    row.querySelector('[name*="model_no"]').value = material.model_no || '';
    row.querySelector('[name*="description"]').value = material.description || '';

    const dropdown = row.querySelector('.suggestions');
    if (dropdown) dropdown.style.display = 'none';

    let info = row.querySelector('.existing-serials-info');
    if (!info) {
        info = document.createElement('div');
        info.className = 'existing-serials-info';
        row.querySelector('.serial-container').parentNode.appendChild(info);
    }
    if (material.serials && material.serials.length > 0) {
        info.innerHTML = `<strong>✅ Available Serials (${material.serial_count}):</strong><br>${material.serials.join(', ')}`;
    } else {
        info.innerHTML = `<em>No serial numbers currently in stock.</em>`;
    }
}

function addSerialField(rowId) {
    const container = document.getElementById(`serial-container-${rowId}`);
    const div = document.createElement('div');
    div.className = 'serial-input';
    div.innerHTML = `<input type="text" name="items[${rowId}][serial_number][]" placeholder="Enter new serial number">`;
    container.appendChild(div);
}

function calculateRow(el) {
    const row = el.closest('.item-row');
    const qty = parseFloat(row.querySelector('[name*="quantity"]').value) || 0;
    const rate = parseFloat(row.querySelector('[name*="rate"]').value) || 0;
    const disc = parseFloat(row.querySelector('[name*="discount"]').value) || 0;
    const amount = (qty * rate) - disc;
    row.querySelector('[name*="amount"]').value = amount.toFixed(2);
}

function removeRow(id) {
    document.getElementById(`row-${id}`).remove();
}

// Modal
let currentType = '', currentRow = null;

function openAddModal(btn, type) {
    currentRow = btn.closest('.item-row');
    currentType = type;
    document.getElementById('modalTitle').textContent = type === 'category' ? 'Add New Category' : 'Add New UOM';
    document.getElementById('modalName').value = '';
    document.getElementById('addModal').style.display = 'flex';
}

function closeModal() {
    document.getElementById('addModal').style.display = 'none';
}

function saveModal() {
    const name = document.getElementById('modalName').value.trim();
    if (!name) return alert("Name is required!");
    const action = currentType === 'category' ? 'add_category' : 'add_uom';
    fetch('', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: `action=${action}&name=${encodeURIComponent(name)}`
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            const selector = currentType === 'category' ? '.category-select' : '.uom-select';
            document.querySelectorAll(selector).forEach(sel => {
                const opt = document.createElement('option');
                opt.value = data.id;
                opt.textContent = escapeHtml(data.name);
                sel.appendChild(opt);
            });
            if (currentRow) currentRow.querySelector(selector).value = data.id;
            closeModal();
        }
    });
}

window.onload = () => addNewRow();
</script>
</body>
</html>