<?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';

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

// Verify Project Access
$check = $conn->prepare("
    SELECT p.project_name, p.project_code 
    FROM project_master p
    LEFT JOIN project_managers pm ON p.id = pm.project_id
    WHERE p.id = ? AND pm.user_id = ?
");
$check->bind_param("ii", $project_id, $user_id);
$check->execute();
$project = $check->get_result()->fetch_assoc();

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

// Fetch Items
$items_result = $conn->query("SELECT id, name, uom FROM inventory_master ORDER BY name ASC");

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

// Handle Form Submission
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $pr_date     = $_POST['pr_date'] ?? date('Y-m-d');
    $required_by = $_POST['required_by'] ?? '';
    $remarks     = trim($_POST['remarks'] ?? '');

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

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

    if (empty($pr_date)) {
        $error = "PR Date is required.";
    } elseif ($valid_items === 0) {
        $error = "Please add at least one item with quantity > 0.";
    } else {
        try {
            $conn->begin_transaction();

            $pr_stmt = $conn->prepare("
                INSERT INTO procurement_request 
                (project_id, requested_by, pr_date, required_by_date, remarks, status, created_at)
                VALUES (?, ?, ?, ?, ?, 'Pending', NOW())
            ");
            $pr_stmt->bind_param("iisss", $project_id, $user_id, $pr_date, $required_by, $remarks);
            $pr_stmt->execute();
            $pr_id = $conn->insert_id;

            $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 = $_POST['uom'][$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 Created Successfully!<br>
                        <strong>PR-" . str_pad($pr_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>Raise Procurement Request</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;
        }
        .container { max-width: 1250px; 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.4rem; 
            font-weight: 700; 
            margin-bottom: 10px;
        }
        .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);
        }

        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin: 25px 0;
            background: rgba(0,0,0,0.2);
            border-radius: 16px;
            /* overflow: hidden; */
        }
        .items-table th {
            background: rgba(168,85,247,0.25);
            padding: 16px;
            text-align: left;
        }
        .items-table td {
            padding: 16px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            position: relative;
        }

        .remove-row {
            color: #ef4444;
            cursor: pointer;
            font-size: 1.5rem;
        }

        .add-row-btn, .submit-btn {
            width: 100%;
            padding: 18px;
            border-radius: 16px;
            font-weight: 700;
            font-size: 1.1rem;
            cursor: pointer;
            margin: 25px 0;
        }
        .add-row-btn {
            background: rgba(34,197,94,0.2);
            color: #86efac;
            border: 1px solid rgba(34,197,94,0.4);
        }
        .submit-btn {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            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; }

        /* Search Suggestions */
        .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);
        }
    </style>
</head>
<body>
<?php include '../config/header.php'; ?>

<div class="container">
    <div class="glass-container">
        <div class="header">
            <a href="../project/project_dashboard.php?id=<?= $project_id ?>" style="color:#c4b5fd; text-decoration:none;">
                ← Back to Dashboard
            </a>
            <h1><i class="fas fa-file-import"></i> Raise Procurement Request</h1>
        </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($project['project_name']) ?> 
                (<?= htmlspecialchars($project['project_code']) ?>)
            </div>

            <form method="post">
                <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(280px,1fr)); gap:20px; margin-bottom:30px;">
                    <div>
                        <label>PR Date <span style="color:#fca5a5;">*</span></label>
                        <input type="date" name="pr_date" value="<?= date('Y-m-d') ?>" required>
                    </div>
                    <div>
                        <label>Required By Date</label>
                        <input type="date" name="required_by">
                    </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..."></textarea>
                </div>

                <button type="submit" class="submit-btn">
                    <i class="fas fa-paper-plane"></i> Submit Procurement Request
                </button>
            </form>
        </div>
    </div>
</div>

<script>
// JavaScript - All functions defined before use
let rowCount = 0;

function addItemRow() {
    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..." 
               onkeyup="searchByModel(this)">
        <input type="hidden" name="item_id[]">  <!-- ✅ IMPORTANT -->
    </td>

    <td><input type="text" name="description[]" placeholder="Item Description"></td>

    <td><input type="number" name="quantity[]" step="0.001" min="0.001" required></td>

    <td><input type="text" name="uom[]" readonly></td>

    <td><span class="remove-row" onclick="this.parentElement.parentElement.remove()">✕</span></td>
`;
}

function updateUnit(select) {
    const row = select.closest('tr');
    const unitCell = row.querySelector('.unit-cell');
    const option = select.options[select.selectedIndex];
    unitCell.textContent = option.dataset.unit || '—';
}

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

    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 matching material found.</div>`;
            } else {
                data.forEach(item => {
                    const div = document.createElement('div');
                    div.className = 'suggestion-item';
                    div.innerHTML = `<strong>${item.model_no || item.name}</strong> — ${item.name}`;
                    div.onclick = () => {
                        selectMaterial(row, item);
                        dropdown.style.display = 'none';
                    };
                    dropdown.appendChild(div);
                });
            }
            dropdown.style.display = 'block';
        })
        .catch(() => dropdown.style.display = 'none');
}

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[]"]');

    if (itemIdInput) itemIdInput.value = material.id;   // ✅ IMPORTANT
    if (nameInput) nameInput.value = material.name || '';
    if (uomInput) uomInput.value = material.uom || '';
    if (modelInput) modelInput.value = material.model_no || '';
}

// Initialize with one row when page loads
window.onload = function() {
    addItemRow();
};
</script>

</body>
</html>

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