<?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']) || $_SESSION['role'] !== 'admin') { // Change role as per your system
    header("Location: ../login.php");
    exit();
}

// Generate Project Code
function generateProjectCode(mysqli $conn): string {
    $sql = "SELECT project_code FROM project_master ORDER BY id DESC LIMIT 1";
    $res = $conn->query($sql);
    $next = 1;
    if ($res && $row = $res->fetch_assoc()) {
        $next = (int)substr($row['project_code'], 4) + 1;
    }
    return sprintf("PRJ-%03d", $next);
}

$success = "";
$error = "";
$generated_code = generateProjectCode($conn);

// Fetch Project Managers
$managers_result = $conn->query("
    SELECT id, full_name 
    FROM users 
    WHERE role = 'project manager' 
    ORDER BY full_name ASC
");

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $project_code           = trim($_POST['project_code'] ?? '');
    $project_name           = trim($_POST['project_name'] ?? '');
    $client_name            = trim($_POST['client_name'] ?? '');
    $project_address        = trim($_POST['project_address'] ?? '');
    $gst_number             = trim($_POST['gst_number'] ?? '');
    $start_date             = $_POST['start_date'] ?: null;
    $end_date               = $_POST['end_date'] ?: null;
    $project_contract_value = (float)($_POST['project_contract_value'] ?? 0);
    $project_budget         = (float)($_POST['project_budget'] ?? 0);
    $po_number              = trim($_POST['po_number'] ?? '');
    $po_date                = $_POST['po_date'] ?: null;
    $project_status         = $_POST['project_status'] ?? 'Planning';

    $project_manager_ids = array_filter(array_map('intval', $_POST['project_manager_ids'] ?? []));

    // Milestones
    $milestone_names   = $_POST['milestone_name'] ?? [];
    $milestone_amounts = $_POST['milestone_amount'] ?? [];
    $milestone_dates   = $_POST['milestone_date'] ?? [];

    if (empty($project_name)) {
        $error = "Project Name is required.";
    } elseif (empty($project_manager_ids)) {
        $error = "Please select at least one Project Manager.";
    } else {
        try {
            $conn->begin_transaction();

            // Insert into project_master
            $stmt = $conn->prepare("
                INSERT INTO project_master (
                    project_code, project_name, client_name, project_address, gst_number,
                    start_date, end_date, project_contract_value, project_budget,
                    po_number, po_date, project_status
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->bind_param("ssssssssssss",
                $project_code, $project_name, $client_name, $project_address, $gst_number,
                $start_date, $end_date, $project_contract_value, $project_budget,
                $po_number, $po_date, $project_status
            );
            $stmt->execute();
            $project_id = $conn->insert_id;

            // Insert Project Managers
            $mgr_stmt = $conn->prepare("INSERT INTO project_managers (project_id, user_id) VALUES (?, ?)");
            foreach ($project_manager_ids as $mid) {
                $mgr_stmt->bind_param("ii", $project_id, $mid);
                $mgr_stmt->execute();
            }

            // Insert Payment Milestones
            if (!empty($milestone_names)) {
                $milestone_stmt = $conn->prepare("
                    INSERT INTO project_milestones (project_id, milestone_name, amount, due_date) 
                    VALUES (?, ?, ?, ?)
                ");
                foreach ($milestone_names as $i => $name) {
                    $name   = trim($name);
                    $amount = (float)($milestone_amounts[$i] ?? 0);
                    $date   = !empty($milestone_dates[$i]) ? $milestone_dates[$i] : null;

                    if (!empty($name) && $amount > 0) {
                        $milestone_stmt->bind_param("isds", $project_id, $name, $amount, $date);
                        $milestone_stmt->execute();
                    }
                }
            }

            // Handle File Attachments
            $upload_dir = "../uploads/projects/" . $project_id . "/";
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }

            $allowed_types = ['pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png'];
            $max_size = 10 * 1024 * 1024; // 10MB

            if (!empty($_FILES['attachments']['name'][0])) {
                $attach_stmt = $conn->prepare("
                    INSERT INTO project_attachments 
                    (project_id, file_name, original_name, file_path, file_size, file_type, uploaded_by) 
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");

                foreach ($_FILES['attachments']['name'] as $key => $original_name) {
                    if ($_FILES['attachments']['error'][$key] !== UPLOAD_ERR_OK) continue;

                    $tmp_name   = $_FILES['attachments']['tmp_name'][$key];
                    $size       = $_FILES['attachments']['size'][$key];
                    $type       = $_FILES['attachments']['type'][$key];

                    $ext = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));

                    if (!in_array($ext, $allowed_types) || $size > $max_size || $size === 0) {
                        continue; // Skip invalid files
                    }

                    $new_file_name = uniqid('proj_') . '.' . $ext;
                    $file_path     = $upload_dir . $new_file_name;
                    $db_path       = "uploads/projects/" . $project_id . "/" . $new_file_name;

                    if (move_uploaded_file($tmp_name, $file_path)) {
                        $attach_stmt->bind_param("isssisi",
                            $project_id,
                            $new_file_name,
                            $original_name,
                            $db_path,
                            $size,
                            $type,
                            $_SESSION['user_id']
                        );
                        $attach_stmt->execute();
                    }
                }
            }

            $conn->commit();
            $success = "Project <strong>" . htmlspecialchars($project_name) . "</strong> created successfully!";

            // Redirect to avoid resubmission
            header("Location: project-management.php?success=1");
            exit();

        } catch (Exception $e) {
            $conn->rollback();
            $error = "Database 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 New Project</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.09);
            --glass-border: rgba(255,255,255,0.18);
        }
        * { 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: 1100px; 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: 50px 40px;
            text-align: center;
        }
        .header h1 { font-size: clamp(28px, 5vw, 40px); font-weight: 700; }

        .form-area { padding: 45px 40px; }

        .section-title {
            font-size: 1.4rem;
            margin: 40px 0 18px;
            color: #e0e7ff;
            border-bottom: 1px solid rgba(255,255,255,0.15);
            padding-bottom: 12px;
        }

        label { display: block; margin-bottom: 8px; font-weight: 600; color: #e0e7ff; }
        input, select {
            width: 100%;
            padding: 16px 18px;
            background: rgba(255,255,255,0.09);
            border: 1px solid rgba(255,255,255,0.25);
            border-radius: 14px;
            color: white;
            font-size: 16px;
        }
        input:focus, select:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(168,85,247,0.25);
        }
        option{
            color:black;
        }
        input[type="checkbox"] { width: auto; }
        .milestone-row {
            display: grid;
            grid-template-columns: 2fr 1fr 1fr 50px;
            gap: 15px;
            margin-bottom: 15px;
            align-items: end;
        }
        .remove-milestone {
            color: #ef4444;
            font-size: 1.8rem;
            cursor: pointer;
            padding-bottom: 8px;
        }

        .add-btn, .submit-btn {
            width: 100%;
            padding: 16px;
            border-radius: 14px;
            font-weight: 700;
            cursor: pointer;
            margin: 15px 0;
        }
        .add-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;
            font-size: 1.15rem;
        }

        .attachment-area {
            border: 2px dashed rgba(168,85,247,0.5);
            border-radius: 16px;
            padding: 40px 20px;
            text-align: center;
            background: rgba(255,255,255,0.03);
            transition: 0.3s;
        }
        .attachment-area:hover { border-color: var(--primary); background: rgba(168,85,247,0.08); }

        .file-list .file-item {
            background: rgba(0,0,0,0.3);
            padding: 12px 16px;
            border-radius: 12px;
            margin: 8px 0;
            display: flex;
            justify-content: space-between;
        }

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

        @media (max-width: 768px) {
            .milestone-row { grid-template-columns: 1fr; }
            .form-area { padding: 30px 20px; }
        }
    </style>
</head>
<body>
<?php include '../config/header.php'; ?>

<div class="container">
    <div class="glass-container">
        <div class="header">
            <h1><i class="fas fa-folder-plus"></i> Add New Project</h1>
            <p style="margin-top:12px; opacity:0.9;">Create project with milestones & attachments</p>
        </div>

        <div class="form-area">
            <?php if (!empty($success) || isset($_GET['success'])): ?>
                <div class="message success">
                    <i class="fas fa-check-circle"></i> Project created successfully!
                </div>
            <?php endif; ?>

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

            <form method="post" enctype="multipart/form-data" id="projectForm">

                <!-- Project Code -->
                <div class="form-group">
                    <label>Project Code <span style="color:#f87171;">*</span></label>
                    <input type="text" name="project_code" value="<?= htmlspecialchars($generated_code) ?>" readonly>
                </div>

                <div class="form-group">
                    <label>Project Name <span style="color:#f87171;">*</span></label>
                    <input type="text" name="project_name" required placeholder="Enter project name">
                </div>
                <div class="form-group">
                    <label>Project Status <span style="color:#f87171;">*</span></label>
                    <Select name="project_status">
                        <option value="">Select Status</option>
                        <option value="Planning">Planning</option>
                        <option value="In Progress">In Progress</option>
                        <option value="Completed">Completed</option>
                        <option value="On Hold">On Hold</option>
                        <option value="Cancelled">Cancelled</option>
                        <option value="Active">Active</option>
                    </Select>
                </div>

                <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(280px,1fr)); gap:20px;">
                    <div class="form-group">
                        <label>Client Name</label>
                        <input type="text" name="client_name" placeholder="Client / Company">
                    </div>
                    <div class="form-group">
                        <label>GST Number</label>
                        <input type="text" name="gst_number" placeholder="22AAAAA0000A1Z5">
                    </div>
                </div>

                <div class="form-group">
                    <label>Project Address</label>
                    <input type="text" name="project_address" placeholder="Full address">
                </div>

                <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:20px;">
                    <div class="form-group"><label>Start Date</label><input type="date" name="start_date"></div>
                    <div class="form-group"><label>End Date</label><input type="date" name="end_date"></div>
                    <div class="form-group"><label>Contract Value (₹)</label><input type="number" name="project_contract_value" step="0.01"></div>
                    <div class="form-group"><label>Budget (₹)</label><input type="number" name="project_budget" step="0.01"></div>
                </div>

                <!-- Project Managers -->
                <div class="form-group">
                    <label>Project Manager(s) <span style="color:#f87171;">*</span></label>
                    <div style="background:rgba(255,255,255,0.07); padding:20px; border-radius:16px; max-height:280px; overflow-y:auto;">
                        <?php while ($m = $managers_result->fetch_assoc()): ?>
                            <div style="margin:10px 0; display:flex; align-items:center; gap:12px;">
                                <input type="checkbox" name="project_manager_ids[]" value="<?= $m['id'] ?>" id="pm_<?= $m['id'] ?>">
                                <label for="pm_<?= $m['id'] ?>" style="cursor:pointer;"><?= htmlspecialchars($m['full_name']) ?></label>
                            </div>
                        <?php endwhile; ?>
                    </div>
                </div>

                <!-- Payment Milestones -->
                <div class="section-title"><i class="fas fa-chart-line"></i> Payment Milestones</div>
                <div id="milestonesContainer"></div>
                <button type="button" class="add-btn" onclick="addMilestoneRow()">
                    <i class="fas fa-plus"></i> Add Milestone
                </button>

                <!-- Attachments -->
                <div class="section-title"><i class="fas fa-paperclip"></i> Project Attachments</div>
                <div class="attachment-area" id="dropZone">
                    <i class="fas fa-cloud-upload-alt" style="font-size:3.5rem; opacity:0.7; margin-bottom:15px;"></i>
                    <p><strong>Drop files here</strong> or click to browse</p>
                    <small>Allowed: PDF, DOC, DOCX, JPG, PNG (Max 10MB each)</small>
                    <input type="file" name="attachments[]" id="fileInput" multiple style="display:none;">
                </div>
                <div class="file-list" id="fileList"></div>

                <button type="submit" class="submit-btn">
                    <i class="fas fa-folder-plus"></i> Create Project
                </button>
            </form>
        </div>
    </div>
</div>

<script>
let milestoneCount = 0;

function addMilestoneRow(name = '', amount = '', date = '') {
    milestoneCount++;
    const container = document.getElementById('milestonesContainer');
    const row = document.createElement('div');
    row.className = 'milestone-row';
    row.innerHTML = `
        <div>
            <label>Milestone Name</label>
            <input type="text" name="milestone_name[]" value="${name}" placeholder="e.g. 30% Advance">
        </div>
        <div>
            <label>Amount (₹)</label>
            <input type="number" name="milestone_amount[]" value="${amount}" step="0.01" placeholder="500000">
        </div>
        <div>
            <label>Due Date</label>
            <input type="date" name="milestone_date[]" value="${date}">
        </div>
        <div><span class="remove-milestone" onclick="this.closest('.milestone-row').remove()">✕</span></div>
    `;
    container.appendChild(row);
}

// Initialize one milestone row
window.onload = () => addMilestoneRow();

// File Upload UI
const dropZone = document.getElementById('dropZone');
const fileInput = document.getElementById('fileInput');
const fileList = document.getElementById('fileList');

dropZone.addEventListener('click', () => fileInput.click());

fileInput.addEventListener('change', () => handleFiles(fileInput.files));

dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.style.borderColor = '#a855f7'; });
dropZone.addEventListener('dragleave', () => dropZone.style.borderColor = 'rgba(168,85,247,0.5)');
dropZone.addEventListener('drop', e => {
    e.preventDefault();
    dropZone.style.borderColor = 'rgba(168,85,247,0.5)';
    handleFiles(e.dataTransfer.files);
});

function handleFiles(files) {
    Array.from(files).forEach(file => {
        if (file.size > 10*1024*1024) return;
        const item = document.createElement('div');
        item.className = 'file-item';
        item.innerHTML = `<span><i class="fas fa-file"></i> ${file.name}</span><small>${(file.size/1024/1024).toFixed(2)} MB</small>`;
        fileList.appendChild(item);
    });
}
</script>
</body>
</html>

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