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

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

$user_id = $_SESSION['user_id'];
$full_name = $_SESSION['full_name'] ?? 'Project Manager';

$pr_id = isset($_GET['pr_id']) ? (int)$_GET['pr_id'] : 0;
if ($pr_id <= 0) {
    die("<h2 style='color:#ef4444;text-align:center;padding:100px;'>No Procurement Request Selected</h2>");
}

// Fetch PR Details + Verify Access
$stmt = $conn->prepare("
    SELECT pr.*, p.project_name, p.project_code 
    FROM procurement_request pr
    JOIN project_master p ON pr.project_id = p.id
    LEFT JOIN project_managers pm ON p.id = pm.project_id
    WHERE pr.id = ? 
      AND pr.requested_by = ? 
      AND pm.user_id = ?
");
$stmt->bind_param("iii", $pr_id, $user_id, $user_id);
$stmt->execute();
$pr = $stmt->get_result()->fetch_assoc();

if (!$pr) {
    die("<h2 style='color:#ef4444;text-align:center;padding:100px;'>Request Not Found or Access Denied</h2>");
}

// Only allow editing if status is Pending
if ($pr['status'] !== 'Pending') {
    die("<h2 style='color:#f59e0b;text-align:center;padding:100px;'>This request cannot be edited.<br>Current Status: <strong>" . htmlspecialchars($pr['status']) . "</strong></h2>");
}

// Fetch Items for this PR
$items_stmt = $conn->prepare("
    SELECT pri.*, im.name, im.uom, im.model_no 
    FROM procurement_request_items pri
    JOIN inventory_master im ON pri.item_id = im.id
    WHERE pri.pr_id = ?
    ORDER BY pri.id ASC
");
$items_stmt->bind_param("i", $pr_id);
$items_stmt->execute();
$existing_items = $items_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Fetch All Inventory Items for Search
$inventory_result = $conn->query("SELECT id, name, uom, model_no FROM inventory_master ORDER BY name ASC");
$inventory = $inventory_result->fetch_all(MYSQLI_ASSOC);

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

// Handle Form Submission
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $pr_date     = $_POST['pr_date'] ?? $pr['pr_date'];
    $required_by = $_POST['required_by'] ?? $pr['required_by_date'];
    $remarks     = trim($_POST['remarks'] ?? $pr['remarks']);

    $item_ids    = $_POST['item_id'] ?? [];
    $quantities  = $_POST['quantity'] ?? [];
    $uoms        = $_POST['uom'] ?? [];

    $valid_items = 0;
    foreach ($quantities as $q) {
        if (!empty($q) && (float)$q > 0) $valid_items++;
    }

    if ($valid_items === 0) {
        $error = "Please add at least one item with quantity > 0.";
    } else {
        try {
            $conn->begin_transaction();

            // Update main PR
            $update_pr = $conn->prepare("
                UPDATE procurement_request 
                SET pr_date = ?, required_by_date = ?, remarks = ?, updated_at = NOW()
                WHERE id = ?
            ");
            $update_pr->bind_param("sssi", $pr_date, $required_by, $remarks, $pr_id);
            $update_pr->execute();

            // Delete old items
            $conn->query("DELETE FROM procurement_request_items WHERE pr_id = $pr_id");

            // Insert updated items
            $item_stmt = $conn->prepare("
                INSERT INTO procurement_request_items (pr_id, item_id, requested_qty, unit)
                VALUES (?, ?, ?, ?)
            ");

            foreach ($quantities as $idx => $qty) {
                $qty = (float)$qty;
                $item_id = (int)($item_ids[$idx] ?? 0);
                $unit = $uoms[$idx] ?? 'NOS';

                if ($qty > 0 && $item_id > 0) {
                    $item_stmt->bind_param("iids", $pr_id, $item_id, $qty, $unit);
                    $item_stmt->execute();
                }
            }

            $conn->commit();
            $success = "Procurement Request Updated Successfully!<br>
                        <strong>PR-" . str_pad($pr_id, 5, '0', STR_PAD_LEFT) . "</strong>";

            // Refresh data
            header("Location: pr_list.php");
            exit();

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Procurement Request - PR-<?= str_pad($pr_id, 5, '0', STR_PAD_LEFT) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    
    <style>
        :root {
            --primary: #a855f7;
            --accent: #c084fc;
            --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;
            padding: 20px 15px;
            min-height: 100vh;
        }
        .container { max-width: 1280px; margin: auto; }
        .glass-container {
            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: 45px 40px;
            text-align: center;
        }
        .header h1 { 
            font-size: 2.3rem; 
            font-weight: 700; 
            margin-bottom: 8px;
        }
        .form-area { padding: 40px; }

        .summary {
            background: rgba(255,255,255,0.08);
            border: 1px solid rgba(255,255,255,0.18);
            border-radius: 20px;
            padding: 20px;
            margin-bottom: 30px;
            text-align: center;
            font-size: 1.1rem;
        }

        label { 
            display: block; 
            margin-bottom: 8px; 
            font-weight: 600; 
            color: #e0e7ff; 
        }
        input, select, textarea {
            width: 100%;
            padding: 14px 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, textarea:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(168,85,247,0.25);
            outline: none;
        }

        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin: 25px 0;
            background: rgba(0,0,0,0.25);
            border-radius: 16px;
            /* overflow: hidden; */
        }
        .items-table th {
            background: rgba(168,85,247,0.3);
            padding: 16px 14px;
            text-align: left;
            font-weight: 600;
        }
        .items-table td {
            padding: 14px;
            border-bottom: 1px solid rgba(255,255,255,0.08);
            vertical-align: top;
        }

        .remove-row {
            color: #ef4444;
            cursor: pointer;
            font-size: 1.6rem;
            transition: all 0.2s;
        }
        .remove-row:hover { transform: scale(1.2); }

        .add-row-btn, .submit-btn {
            width: 100%;
            padding: 18px;
            border-radius: 16px;
            font-weight: 700;
            font-size: 1.1rem;
            cursor: pointer;
            margin: 20px 0;
            transition: all 0.3s;
        }
        .add-row-btn {
            background: rgba(34,197,94,0.2);
            color: #86efac;
            border: 1px solid rgba(34,197,94,0.5);
        }
        .add-row-btn:hover {
            background: rgba(34,197,94,0.35);
        }
        .submit-btn {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            border: none;
        }
        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(168,85,247,0.4);
        }

        .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; }

        .suggestions {
            position: absolute;
            z-index: 1000;
            background: #1f2937;
            border: 1px solid #a855f7;
            border-radius: 12px;
            max-height: 260px;
            overflow-y: auto;
            width: 100%;
            margin-top: 4px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.7);
        }
        .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.35);
        }

        @media (max-width: 768px) {
            .header h1 { font-size: 1.9rem; }
            .form-area { padding: 25px 20px; }
            .items-table th, .items-table td { padding: 12px 8px; font-size: 0.95rem; }
        }
    </style>
</head>
<body>
<?php include '../config/header.php'; ?>

<div class="container">
    <div class="glass-container">
        <div class="header">
            <a href="view_procurement_requests.php?project_id=<?= $pr['project_id'] ?>" 
               style="color:#c4b5fd; text-decoration:none; font-size:1.1rem;">
                ← Back to Requests
            </a>
            <h1><i class="fas fa-edit"></i> Edit Procurement Request</h1>
            <p style="opacity:0.85; margin-top:8px;">PR-<?= str_pad($pr_id, 5, '0', STR_PAD_LEFT) ?></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; ?>

            <div class="summary">
                <strong>Project:</strong> <?= htmlspecialchars($pr['project_name']) ?> 
                (<?= htmlspecialchars($pr['project_code']) ?>)
            </div>

            <form method="post">
                <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(280px,1fr)); gap:20px; margin-bottom:35px;">
                    <div>
                        <label>PR Date <span style="color:#fca5a5;">*</span></label>
                        <input type="date" name="pr_date" value="<?= htmlspecialchars($pr['pr_date']) ?>" required>
                    </div>
                    <div>
                        <label>Required By Date</label>
                        <input type="date" name="required_by" value="<?= htmlspecialchars($pr['required_by_date'] ?? '') ?>">
                    </div>
                </div>

                <h3 style="margin: 35px 0 15px; color:#e0e7ff;">Required Items</h3>

                <table class="items-table" id="itemsTable">
                    <thead>
                        <tr>
                            <th>Sr.No</th>
                            <th>Model No / Search</th>
                            <th>Item Name</th>
                            <th>Quantity</th>
                            <th>Unit</th>
                            <th style="width:60px;"></th>
                        </tr>
                    </thead>
                    <tbody id="itemsBody"></tbody>
                </table>

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

                <div style="margin-top:30px;">
                    <label>Remarks / Special Instructions</label>
                    <textarea name="remarks" rows="4" placeholder="Any urgency, preferred supplier, delivery notes..."><?= htmlspecialchars($pr['remarks'] ?? '') ?></textarea>
                </div>

                <button type="submit" class="submit-btn">
                    <i class="fas fa-save"></i> Update Procurement Request
                </button>
            </form>
        </div>
    </div>
</div>

<script>
// Global variables
let rowCount = 0;
const inventoryData = <?= json_encode($inventory) ?>;   // All materials for searching

function addItemRow(material = null) {
    rowCount++;
    const tbody = document.getElementById('itemsBody');
    const row = tbody.insertRow();

    row.innerHTML = `
        <td>${rowCount}</td>
        <td style="position:relative;">
            <input type="text" name="model_no[]" placeholder="Type model number or name..." 
                   onkeyup="searchByModel(this)" value="${material ? (material.model_no || '') : ''}">
            <input type="hidden" name="item_id[]" value="${material ? material.id : ''}">
        </td>
        <td><input type="text" name="description[]" placeholder="Item Description" value="${material ? (material.name || '') : ''}"></td>
        <td><input type="number" name="quantity[]" step="0.001" min="0.001" value="${material ? material.requested_qty : ''}" required></td>
        <td><input type="text" name="uom[]" readonly value="${material ? (material.uom || 'NOS') : ''}"></td>
        <td><span class="remove-row" onclick="this.parentElement.parentElement.remove(); updateRowNumbers()">✕</span></td>
    `;

    // If pre-filling from existing items
    if (material && material.id) {
        row.querySelector('input[name="item_id[]"]').value = material.id;
    }
}

function searchByModel(input) {
    const query = input.value.trim().toLowerCase();
    const row = input.closest('tr');
    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;
    }

    const filtered = inventoryData.filter(item => 
        (item.model_no && item.model_no.toLowerCase().includes(query)) ||
        (item.name && item.name.toLowerCase().includes(query))
    );

    dropdown.innerHTML = '';

    if (filtered.length === 0) {
        dropdown.innerHTML = `<div class="suggestion-item" style="color:#888;">No matching material found.</div>`;
    } else {
        filtered.slice(0, 12).forEach(item => {
            const div = document.createElement('div');
            div.className = 'suggestion-item';
            div.innerHTML = `<strong>${item.model_no || '—'}</strong> — ${item.name}`;
            div.onclick = () => {
                selectMaterial(row, item);
                dropdown.style.display = 'none';
            };
            dropdown.appendChild(div);
        });
    }
    dropdown.style.display = 'block';
}

function selectMaterial(row, material) {
    const itemIdInput = row.querySelector('input[name="item_id[]"]');
    const modelInput  = row.querySelector('input[name="model_no[]"]');
    const nameInput   = row.querySelector('input[name="description[]"]');
    const uomInput    = row.querySelector('input[name="uom[]"]');

    itemIdInput.value = material.id;
    modelInput.value  = material.model_no || '';
    nameInput.value   = material.name || '';
    uomInput.value    = material.uom || 'NOS';
}

function updateRowNumbers() {
    const rows = document.querySelectorAll('#itemsBody tr');
    rows.forEach((row, index) => {
        row.cells[0].textContent = index + 1;
    });
    rowCount = rows.length;
}

// Initialize with existing items
window.onload = function() {
    <?php if (!empty($existing_items)): ?>
        <?php foreach ($existing_items as $item): ?>
            addItemRow(<?= json_encode([
                'id' => $item['item_id'],
                'name' => $item['name'],
                'uom' => $item['uom'],
                'model_no' => $item['model_no'], // Add model_no if you have it in inventory
                'requested_qty' => $item['requested_qty']
            ]) ?>);
        <?php endforeach; ?>
    <?php else: ?>
        addItemRow(); // Add empty row if no items
    <?php endif; ?>
};
</script>

</body>
</html>

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