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

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

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role'];
$full_name = $_SESSION['full_name'] ?? 'Store/Admin';

// Fetch approved PRs (only those not yet converted to PO)
$prs = $conn->query("
    SELECT 
        pr.id, pr.pr_date, pr.project_id, pr.required_by_date,
        p.project_code, p.project_name,
        u.full_name AS raised_by
    FROM procurement_request pr
    LEFT JOIN project_master p ON pr.project_id = p.id
    LEFT JOIN users u ON pr.requested_by = u.id
    WHERE pr.status = 'Approved'
    AND NOT EXISTS (SELECT 1 FROM purchase_order WHERE pr_id = pr.id)
    ORDER BY pr.pr_date DESC
");

// Fetch all items (for manual add)
$items = $conn->query("SELECT id, name, uom FROM inventory_master ORDER BY name ASC");

// Fetch vendors
$vendors = $conn->query("SELECT DISTINCT supplier_vendor FROM inventory_master WHERE supplier_vendor IS NOT NULL AND supplier_vendor != '' ORDER BY supplier_vendor");

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

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $po_date       = $_POST['po_date'] ?? date('Y-m-d');
    $delivery_date = $_POST['delivery_date'] ?? '';
    $vendor        = trim($_POST['vendor'] ?? '');
    $pr_id         = (int)($_POST['pr_id'] ?? 0);
    $terms         = trim($_POST['terms'] ?? '');
    $remarks       = trim($_POST['remarks'] ?? '');

    $item_ids      = $_POST['item_id'] ?? [];
    $quantities    = $_POST['quantity'] ?? [];
    $rates         = $_POST['rate'] ?? [];

    // Validation
    if (empty($po_date)) {
        $error = "PO Date is required.";
    } elseif (empty($vendor)) {
        $error = "Vendor is required.";
    } elseif ($pr_id <= 0) {
        $error = "Please select a valid Approved PR.";
    } elseif (empty($item_ids) || count(array_filter($quantities)) === 0) {
        $error = "Please add at least one item with quantity > 0.";
    } else {
        try {
            $conn->begin_transaction();

            // Insert PO header
            $po_sql = "
                INSERT INTO purchase_order (
                    po_date, delivery_date, vendor, pr_id, project_id,
                    terms_conditions, remarks, status, created_by, created_at
                ) VALUES (?, ?, ?, ?, (SELECT project_id FROM procurement_request WHERE id = ?),
                          ?, ?, 'Issued', ?, NOW())
            ";
            $po_stmt = $conn->prepare($po_sql);
            $po_stmt->bind_param("sssisiisi", $po_date, $delivery_date, $vendor, $pr_id, $pr_id, $terms, $remarks, $user_id);
            $po_stmt->execute();
            $po_id = $conn->insert_id;

            // Insert PO items
            $item_sql = "
                INSERT INTO purchase_order_items (
                    po_id, item_id, ordered_qty, rate, unit
                ) VALUES (?, ?, ?, ?, ?)
            ";
            $item_stmt = $conn->prepare($item_sql);

            foreach ($item_ids as $idx => $item_id) {
                $qty = !empty($quantities[$idx]) ? (float)$quantities[$idx] : 0;
                $rate = !empty($rates[$idx]) ? (float)$rates[$idx] : 0;

                if ($qty > 0) {
                    // Get unit
                    $unit_q = $conn->prepare("SELECT uom FROM inventory_master WHERE id = ?");
                    $unit_q->bind_param("i", $item_id);
                    $unit_q->execute();
                    $unit = $unit_q->get_result()->fetch_assoc()['uom'] ?? 'NOS';
                    $unit_q->close();

                    $item_stmt->bind_param("iidss", $po_id, $item_id, $qty, $rate, $unit);
                    $item_stmt->execute();
                }
            }

            // Update PR status to Converted
            $update_pr = "UPDATE procurement_request SET status = 'Converted to PO' WHERE id = ?";
            $pr_up_stmt = $conn->prepare($update_pr);
            $pr_up_stmt->bind_param("i", $pr_id);
            $pr_up_stmt->execute();

            $conn->commit();

            $success = "Purchase Order created successfully from PR!<br>PO ID: <strong>PO-" . str_pad($po_id, 5, '0', STR_PAD_LEFT) . "</strong>";
        } catch (Exception $e) {
            $conn->rollback();
            $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>Create PO from Approved PR</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --primary: #8b5cf6;
            --success: #22c55e;
            --danger: #ef4444;
            --glass: rgba(255,255,255,0.08);
            --border: rgba(255,255,255,0.15);
        }
        body {
            font-family: 'Segoe UI', system-ui, sans-serif;
            background: linear-gradient(rgba(0,0,0,0.8), rgba(0,0,0,0.95)),
                        url('../background.jpeg') center/cover fixed;
            color: white;
            margin: 0;
            padding: 20px 15px;
        }
        .container { max-width: 1100px; margin: 0 auto; }
        .back { color: #c4b5fd; text-decoration: none; font-weight: 500; display: inline-flex; align-items: center; gap: 8px; margin-bottom: 20px; }
        .back:hover { color: white; }

        h1 { margin: 0 0 8px; font-size: 2rem; }

        .form-area {
            background: var(--glass);
            backdrop-filter: blur(12px);
            border: 1px solid var(--border);
            border-radius: 16px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.4);
        }
        .form-group { margin-bottom: 24px; }
        label { display: block; margin-bottom: 8px; font-weight: 600; font-size: 1.05rem; }
        input, select, textarea {
            width: 100%;
            padding: 14px 16px;
            background: rgba(255,255,255,0.08);
            border: 1px solid rgba(255,255,255,0.2);
            border-radius: 10px;
            color: white;
            font-size: 1rem;
        }
        textarea { min-height: 100px; }

        .items-table {
            width: 100%;
            margin: 20px 0 30px;
            border-collapse: collapse;
        }
        .items-table th, .items-table td { padding: 12px; border-bottom: 1px solid var(--border); text-align: left; }
        .items-table th { background: rgba(255,255,255,0.1); }
        .remove-row { color: var(--danger); cursor: pointer; font-size: 1.3rem; text-align: center; }

        .add-row-btn {
            background: rgba(34,197,94,0.25);
            color: #86efac;
            border: 1px solid rgba(34,197,94,0.4);
            padding: 10px 24px;
            border-radius: 10px;
            cursor: pointer;
            font-weight: 600;
            margin-bottom: 25px;
        }

        .submit-btn {
            background: linear-gradient(135deg, var(--primary), #a78bfa);
            color: white;
            border: none;
            padding: 16px;
            border-radius: 12px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            width: 100%;
            transition: all 0.3s;
        }
        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(139,92,246,0.4);
        }

        .message {
            padding: 16px;
            border-radius: 10px;
            margin-bottom: 25px;
            font-weight: 500;
        }
        .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>

<div class="container">
    <a href="pr_approval_list.php" class="back">
        <i class="fas fa-arrow-left"></i> Back to Pending PRs
    </a>

    <h1>Create Purchase Order from Approved PR</h1>

    <?php if ($success): ?>
        <div class="message success">
            <i class="fas fa-check-circle"></i> <?= $success ?>
        </div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="message error">
            <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($error) ?>
        </div>
    <?php endif; ?>

    <div class="form-area">
        <form method="post">
            <div class="form-group">
                <label for="pr_id">Select Approved PR <span style="color:#fca5a5;">*</span></label>
                <select name="pr_id" id="pr_id" required onchange="loadPRItems(this.value)">
                    <option value="">-- Select PR --</option>
                    <?php while ($pr = $prs->fetch_assoc()): ?>
                        <option value="<?= $pr['id'] ?>">
                            PR-<?= str_pad($pr['id'], 5, '0', STR_PAD_LEFT) ?> 
                            | <?= date('d M Y', strtotime($pr['pr_date'])) ?> 
                            | <?= htmlspecialchars($pr['project_code'] ?? 'Central') ?> - <?= htmlspecialchars($pr['project_name'] ?? 'General') ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>

            <div class="form-group">
                <label for="po_date">PO Date <span style="color:#fca5a5;">*</span></label>
                <input type="date" id="po_date" name="po_date" value="<?= date('Y-m-d') ?>" required>
            </div>

            <div class="form-group">
                <label for="delivery_date">Expected Delivery Date</label>
                <input type="date" id="delivery_date" name="delivery_date">
            </div>

            <div class="form-group">
                <label for="vendor">Vendor / Supplier <span style="color:#fca5a5;">*</span></label>
                <select name="vendor" id="vendor" required>
                    <option value="">Select Vendor</option>
                    <?php while ($v = $vendors->fetch_assoc()): ?>
                        <option value="<?= htmlspecialchars($v['supplier_vendor']) ?>">
                            <?= htmlspecialchars($v['supplier_vendor']) ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>

            <h3 style="margin: 35px 0 15px;">Items from PR (edit quantities/rates if needed)</h3>

            <table class="items-table" id="itemsTable">
                <thead>
                    <tr>
                        <th>Item Name</th>
                        <th>Requested Qty</th>
                        <th>Order Qty</th>
                        <th>Rate (₹)</th>
                        <th>Unit</th>
                        <th>Total (₹)</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <!-- Items will be loaded via JS -->
                </tbody>
            </table>

            <button type="button" class="add-row-btn" onclick="addItemRow()">
                <i class="fas fa-plus"></i> Add Extra Item
            </button>

            <div style="text-align:right; font-size:1.4rem; margin:20px 0; font-weight:700;">
                Grand Total: <span id="grandTotal">₹ 0.00</span>
            </div>

            <div class="form-group">
                <label for="terms">Terms & Conditions</label>
                <textarea name="terms" id="terms" placeholder="Payment terms (e.g. 30 days), delivery location, penalties..."></textarea>
            </div>

            <div class="form-group">
                <label for="remarks">Remarks / Notes</label>
                <textarea name="remarks" id="remarks" placeholder="Special instructions, urgency..."></textarea>
            </div>

            <button type="submit" class="submit-btn">
                <i class="fas fa-save"></i> Create Purchase Order from PR
            </button>
        </form>
    </div>
</div>

<script>
// Add manual row
function addItemRow() {
    const tbody = document.getElementById('itemsTable').getElementsByTagName('tbody')[0];
    const row = tbody.insertRow();

    row.innerHTML = `
        <td>
            <select name="item_id[]" required onchange="updateUnitAndTotal(this)">
                <option value="">Select Item</option>
                <?php 
                $items->data_seek(0);
                while ($item = $items->fetch_assoc()): ?>
                    <option value="<?= $item['id'] ?>" data-unit="<?= htmlspecialchars($item['uom']) ?>">
                        <?= htmlspecialchars($item['name']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
        </td>
        <td>—</td>
        <td><input type="number" name="quantity[]" step="0.001" min="0.001" placeholder="Order Qty" required oninput="updateTotal(this)"></td>
        <td><input type="number" name="rate[]" step="0.01" min="0" placeholder="Rate" required oninput="updateTotal(this)"></td>
        <td class="unit-cell">—</td>
        <td class="line-total">₹ 0.00</td>
        <td><span onclick="this.parentElement.parentElement.remove(); updateGrandTotal()" style="cursor:pointer;color:#ef4444;font-size:1.3rem;">
            <i class="fas fa-trash"></i>
        </span></td>
    `;
}

// Update unit & total when item selected
function updateUnitAndTotal(select) {
    const row = select.parentElement.parentElement;
    const unitCell = row.querySelector('.unit-cell');
    const qtyInput = row.querySelector('input[name="quantity[]"]');
    const rateInput = row.querySelector('input[name="rate[]"]');

    const selected = select.options[select.selectedIndex];
    unitCell.textContent = selected.dataset.unit || '—';

    updateTotal(qtyInput);
}

// Update line total & grand total
function updateTotal(input) {
    const row = input.parentElement.parentElement;
    const qty = parseFloat(row.querySelector('input[name="quantity[]"]').value) || 0;
    const rate = parseFloat(row.querySelector('input[name="rate[]"]').value) || 0;
    const lineTotal = (qty * rate).toFixed(2);
    row.querySelector('.line-total').textContent = `₹ ${lineTotal}`;
    updateGrandTotal();
}

function updateGrandTotal() {
    let total = 0;
    document.querySelectorAll('.line-total').forEach(cell => {
        total += parseFloat(cell.textContent.replace('₹ ', '')) || 0;
    });
    document.getElementById('grandTotal').textContent = `₹ ${total.toFixed(2)}`;
}

// Load PR items via AJAX
function loadPRItems(prId) {
    if (!prId) {
        // Clear table except header
        document.getElementById('itemsTable').getElementsByTagName('tbody')[0].innerHTML = '';
        updateGrandTotal();
        return;
    }

    fetch(`get_pr_items_for_po.php?pr_id=${prId}`)
        .then(response => response.json())
        .then(data => {
            const tbody = document.getElementById('itemsTable').getElementsByTagName('tbody')[0];
            tbody.innerHTML = ''; // Clear existing

            data.forEach(item => {
                const row = tbody.insertRow();
                row.innerHTML = `
                    <td>
                        <select name="item_id[]" required onchange="updateUnitAndTotal(this)">
                            <option value="">Select Item</option>
                            <?php 
                            $items->data_seek(0);
                            while ($opt = $items->fetch_assoc()): ?>
                                <option value="<?= $opt['id'] ?>" data-unit="<?= htmlspecialchars($opt['uom']) ?>" 
                                    ${item.item_id == <?= $opt['id'] ?> ? 'selected' : ''}>
                                    <?= htmlspecialchars($opt['name']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </td>
                    <td>${item.requested_qty}</td>
                    <td><input type="number" name="quantity[]" step="0.001" min="0.001" value="${item.requested_qty}" required oninput="updateTotal(this)"></td>
                    <td><input type="number" name="rate[]" step="0.01" min="0" placeholder="Rate" required oninput="updateTotal(this)"></td>
                    <td class="unit-cell">${item.unit || '—'}</td>
                    <td class="line-total">₹ 0.00</td>
                    <td><span onclick="this.parentElement.parentElement.remove(); updateGrandTotal()" style="cursor:pointer;color:#ef4444;font-size:1.3rem;">
                        <i class="fas fa-trash"></i>
                    </span></td>
                `;
                // Trigger total update
                row.querySelector('input[name="quantity[]"]').dispatchEvent(new Event('input'));
            });
        })
        .catch(err => console.error('Error loading PR items:', err));
}
</script>

</body>
</html>

<?php $conn->close(); ?>