<?php
require_once '../includes/auth.php';
requirePermission('purchases', 'create');
require_once '../db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $vendor_id           = (int)$_POST['vendor_id'];
    $purchase_date       = $_POST['purchase_date'];
    $supplier_invoice_no = trim($_POST['supplier_invoice_no']);

    if (!$vendor_id || !$purchase_date) die('Invalid purchase data');

    $datePart = date('Ymd', strtotime($purchase_date));
    $countRes = $conn->query("SELECT COUNT(*) FROM purchase_orders WHERE purchase_date = '$purchase_date'");
    $seq = str_pad($countRes->fetch_row()[0] + 1, 3, '0', STR_PAD_LEFT);
    $po_no = "PO-$datePart-$seq";

    $stmt = $conn->prepare("
        INSERT INTO purchase_orders (po_no, vendor_id, supplier_invoice_no, purchase_date, company_id)
        VALUES (?, ?, ?, ?, ?)
    ");
    $stmt->bind_param("sissi", $po_no, $vendor_id, $supplier_invoice_no, $purchase_date, $cid);
    $stmt->execute();

    header("Location: edit.php?id=" . $stmt->insert_id);
    exit;
}

require_once '../includes/header.php';
require_once '../includes/sidebar.php';

$vendors = $conn->query("SELECT id, name FROM vendors WHERE status = 1 AND company_id = $cid ORDER BY name");
$vendorList = [];
while ($v = $vendors->fetch_assoc()) $vendorList[] = $v;
?>

<div class="page-header">
    <h2><i class="fas fa-plus-circle" style="color:var(--primary);margin-right:8px;"></i>New Purchase Order</h2>
    <div style="display:flex;gap:8px;">
        <a href="create_ai.php" class="btn btn-outline btn-sm" style="color:var(--primary);border-color:var(--primary);">
            <i class="fas fa-magic"></i> New Purchase via AI
        </a>
        <a href="index.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
    </div>
</div>

<div class="panel" style="max-width:560px;">
    <div class="panel-header"><span class="panel-title">Purchase Details</span></div>
    <div class="panel-body">
        <form method="post" id="poForm">

            <div class="form-group">
                <label>Vendor <span style="color:var(--danger)">*</span></label>
                <input type="hidden" name="vendor_id" id="vendor_id" required>
                <div style="position:relative;">
                    <input type="text" id="vendorSearch" placeholder="Type to search vendor..."
                           autocomplete="off"
                           oninput="filterVendors(this.value)"
                           onfocus="filterVendors(this.value)"
                           style="width:100%;">
                    <div id="vendorDropdown" style="display:none;position:absolute;top:100%;left:0;right:0;background:#fff;border:1px solid var(--border);border-radius:0 0 6px 6px;max-height:220px;overflow-y:auto;z-index:999;box-shadow:0 4px 12px rgba(0,0,0,.12);"></div>
                </div>
                <div id="vendorChosen" style="display:none;margin-top:6px;padding:6px 10px;background:var(--bg-light);border-radius:5px;font-size:13px;display:flex;align-items:center;gap:8px;">
                    <i class="fas fa-truck" style="color:var(--primary);"></i>
                    <span id="vendorChosenName"></span>
                    <button type="button" onclick="clearVendor()" style="margin-left:auto;background:none;border:none;cursor:pointer;color:var(--danger);font-size:13px;"><i class="fas fa-times"></i></button>
                </div>
            </div>

            <div class="form-group">
                <label>Purchase Date <span style="color:var(--danger)">*</span></label>
                <input type="date" name="purchase_date" value="<?= date('Y-m-d') ?>" required>
            </div>

            <div class="form-group">
                <label>Supplier Invoice No <span style="color:var(--text-muted);font-weight:400;text-transform:none;">(optional)</span></label>
                <input type="text" name="supplier_invoice_no" placeholder="e.g. SUP-001">
            </div>

            <div style="display:flex;gap:10px;margin-top:8px;">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-arrow-right"></i> Create & Add Items
                </button>
                <a href="index.php" class="btn btn-secondary">Cancel</a>
            </div>

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

<!-- Add New Vendor Modal -->
<div id="vendorModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.45);z-index:2000;align-items:center;justify-content:center;">
    <div style="background:#fff;border-radius:10px;padding:28px 28px 20px;width:420px;max-width:95vw;box-shadow:0 8px 40px rgba(0,0,0,.2);">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:18px;">
            <h3 style="margin:0;font-size:16px;"><i class="fas fa-truck" style="color:var(--primary);margin-right:8px;"></i>Add New Vendor</h3>
            <button type="button" onclick="closeVendorModal()" style="background:none;border:none;font-size:18px;cursor:pointer;color:var(--text-muted);">&times;</button>
        </div>
        <div class="form-group">
            <label>Vendor / Company Name <span style="color:var(--danger)">*</span></label>
            <input type="text" id="mv_name" placeholder="Vendor name" style="width:100%;">
        </div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
            <div class="form-group"><label>Phone</label><input type="text" id="mv_phone" placeholder="Phone"></div>
            <div class="form-group"><label>Mobile</label><input type="text" id="mv_mobile" placeholder="Mobile"></div>
        </div>
        <div class="form-group">
            <label>GSTIN</label>
            <input type="text" id="mv_gstin" placeholder="15-digit GSTIN" maxlength="15" style="text-transform:uppercase;"
                   oninput="this.value=this.value.toUpperCase();">
        </div>
        <div id="mv_error" style="color:var(--danger);font-size:13px;margin-bottom:8px;display:none;"></div>
        <div style="display:flex;gap:10px;justify-content:flex-end;margin-top:8px;">
            <button type="button" class="btn btn-secondary" onclick="closeVendorModal()">Cancel</button>
            <button type="button" class="btn btn-primary" onclick="saveNewVendor()"><i class="fas fa-save"></i> Save & Select</button>
        </div>
    </div>
</div>

<script>
const VENDORS = <?= json_encode($vendorList) ?>;

function filterVendors(q) {
    const dd = document.getElementById('vendorDropdown');
    const search = q.trim().toLowerCase();
    const filtered = search ? VENDORS.filter(v => v.name.toLowerCase().includes(search)) : VENDORS;
    let html = '';
    filtered.slice(0, 30).forEach(v => {
        html += `<div class="vdd-item" onmousedown="selectVendor(${v.id}, '${v.name.replace(/'/g,"\\'")}')">
            <i class="fas fa-truck" style="color:var(--primary);margin-right:7px;font-size:12px;"></i>${v.name}</div>`;
    });
    html += `<div class="vdd-item vdd-add" onmousedown="openVendorModal('${q.replace(/'/g,"\\'")}')">
        <i class="fas fa-plus-circle" style="color:var(--success);margin-right:7px;"></i>Add New Vendor${q.trim() ? ' "'+q.trim()+'"' : ''}</div>`;
    dd.innerHTML = html;
    dd.style.display = 'block';
}
document.getElementById('vendorSearch').addEventListener('blur', function() {
    setTimeout(() => document.getElementById('vendorDropdown').style.display = 'none', 150);
});
function selectVendor(id, name) {
    document.getElementById('vendor_id').value = id;
    document.getElementById('vendorSearch').style.display = 'none';
    document.getElementById('vendorDropdown').style.display = 'none';
    const chosen = document.getElementById('vendorChosen');
    chosen.style.display = 'flex';
    document.getElementById('vendorChosenName').textContent = name;
}
function clearVendor() {
    document.getElementById('vendor_id').value = '';
    document.getElementById('vendorSearch').style.display = '';
    document.getElementById('vendorSearch').value = '';
    document.getElementById('vendorChosen').style.display = 'none';
    document.getElementById('vendorSearch').focus();
}
function openVendorModal(prefill) {
    document.getElementById('mv_name').value = prefill || '';
    document.getElementById('mv_phone').value = '';
    document.getElementById('mv_mobile').value = '';
    document.getElementById('mv_gstin').value = '';
    document.getElementById('mv_error').style.display = 'none';
    document.getElementById('vendorModal').style.display = 'flex';
    document.getElementById('mv_name').focus();
}
function closeVendorModal() { document.getElementById('vendorModal').style.display = 'none'; }
function saveNewVendor() {
    const name = document.getElementById('mv_name').value.trim();
    const errEl = document.getElementById('mv_error');
    if (!name) { errEl.textContent = 'Vendor name is required.'; errEl.style.display='block'; return; }
    errEl.style.display = 'none';
    const fd = new FormData();
    fd.append('name',   name);
    fd.append('phone',  document.getElementById('mv_phone').value.trim());
    fd.append('mobile', document.getElementById('mv_mobile').value.trim());
    fd.append('gstin',  document.getElementById('mv_gstin').value.trim());
    fetch('ajax_add_vendor.php', { method:'POST', body: fd })
    .then(r => r.json())
    .then(data => {
        if (data.status === 'ok') {
            VENDORS.push({id: data.id, name: data.name});
            VENDORS.sort((a,b) => a.name.localeCompare(b.name));
            closeVendorModal();
            selectVendor(data.id, data.name);
        } else { errEl.textContent = data.message || 'Error saving vendor.'; errEl.style.display='block'; }
    })
    .catch(() => { errEl.textContent = 'Server error. Try again.'; errEl.style.display='block'; });
}
document.getElementById('poForm').addEventListener('submit', function(e) {
    if (!document.getElementById('vendor_id').value) {
        e.preventDefault();
        document.getElementById('vendorSearch').focus();
        document.getElementById('vendorSearch').style.borderColor = 'var(--danger)';
    }
});
</script>

<style>
.vdd-item { padding:8px 12px;cursor:pointer;font-size:13px;border-bottom:1px solid #f0f0f0; }
.vdd-item:hover { background:var(--bg-light); }
.vdd-add { color:var(--success);font-weight:500;border-top:2px solid #f0f0f0;border-bottom:none; }
</style>

<?php require_once '../includes/footer.php'; ?>
