<?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') {
    header("Location: ../login.php");
    exit();
}

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

// Handle Attachment Delete (AJAX-style via GET)
if (isset($_GET['delete_attachment'])) {
    $attach_id = (int)$_GET['delete_attachment'];
    
    $stmt = $conn->prepare("SELECT file_path FROM project_attachments WHERE id = ? AND project_id = ?");
    $stmt->bind_param("ii", $attach_id, $project_id);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();

    if ($result) {
        $full_path = "../" . $result['file_path'];
        if (file_exists($full_path)) {
            unlink($full_path);
        }
        $conn->query("DELETE FROM project_attachments WHERE id = $attach_id");
        header("Location: edit-project.php?id=$project_id&success=Attachment deleted successfully");
        exit();
    }
}

// Fetch Project Details
$stmt = $conn->prepare("SELECT * FROM project_master WHERE id = ?");
$stmt->bind_param("i", $project_id);
$stmt->execute();
$project = $stmt->get_result()->fetch_assoc();

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

// Fetch Assigned Managers
$assigned_managers = [];
$res = $conn->query("SELECT user_id FROM project_managers WHERE project_id = $project_id");
while ($row = $res->fetch_assoc()) $assigned_managers[] = $row['user_id'];

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

// Fetch Milestones
$milestones = $conn->query("
    SELECT * FROM project_milestones WHERE project_id = $project_id ORDER BY due_date ASC
")->fetch_all(MYSQLI_ASSOC);

// Fetch Attachments
$attachments = $conn->query("
    SELECT * FROM project_attachments WHERE project_id = $project_id ORDER BY created_at DESC
")->fetch_all(MYSQLI_ASSOC);

$success = isset($_GET['success']) ? $_GET['success'] : "";
$error = "";

// Handle POST - Update Project
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $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'] ?? []));

    $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();

            // Update Project
            $stmt = $conn->prepare("
                UPDATE project_master SET 
                    project_name=?, client_name=?, project_address=?, gst_number=?,
                    start_date=?, end_date=?, project_contract_value=?, project_budget=?,
                    po_number=?, po_date=?, project_status=?, updated_at=NOW()
                WHERE id=?
            ");
            $stmt->bind_param("sssssssssssi", 
                $project_name, $client_name, $project_address, $gst_number,
                $start_date, $end_date, $project_contract_value, $project_budget,
                $po_number, $po_date, $project_status, $project_id
            );
            $stmt->execute();

            // Update Managers
            $conn->query("DELETE FROM project_managers WHERE project_id = $project_id");
            $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();
            }

            // Update Milestones
            $conn->query("DELETE FROM project_milestones WHERE project_id = $project_id");
            if (!empty($milestone_names)) {
                $ms_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) {
                        $ms_stmt->bind_param("isds", $project_id, $name, $amount, $date);
                        $ms_stmt->execute();
                    }
                }
            }

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

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

            if (!empty($_FILES['attachments']['name'][0])) {
                $att_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 $k => $orig_name) {
                    if ($_FILES['attachments']['error'][$k] !== 0) continue;

                    $tmp = $_FILES['attachments']['tmp_name'][$k];
                    $size = $_FILES['attachments']['size'][$k];
                    $type = $_FILES['attachments']['type'][$k];
                    $ext = strtolower(pathinfo($orig_name, PATHINFO_EXTENSION));

                    if (!in_array($ext, $allowed) || $size > $max_size) continue;

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

                    if (move_uploaded_file($tmp, $full_path)) {
                        $att_stmt->bind_param("isssisi", $project_id, $new_name, $orig_name, $db_path, $size, $type, $_SESSION['user_id']);
                        $att_stmt->execute();
                    }
                }
            }

            $conn->commit();
            header("Location: edit-project.php?id=$project_id&success=Project updated successfully");
            exit();

        } catch (Exception $e) {
            $conn->rollback();
            $error = "Update failed: " . $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 Project - <?= htmlspecialchars($project['project_name']) ?></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: 45px 40px;
            text-align: center;
        }
        .header h1 { font-size: clamp(26px, 5vw, 36px); font-weight: 700; }

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

        .section-title {
            font-size: 1.35rem;
            margin: 35px 0 15px;
            color: #e0e7ff;
            border-bottom: 1px solid rgba(255,255,255,0.15);
            padding-bottom: 10px;
        }

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

        .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:35px 20px;
            text-align:center; background:rgba(255,255,255,0.03);
        }
        .file-item {
            background:rgba(0,0,0,0.3); padding:12px 16px; border-radius:12px; margin:8px 0;
            display:flex; justify-content:space-between; align-items:center;
        }
        .delete-btn {
            color:#ef4444; cursor:pointer; font-size:1.1rem;
        }
        .delete-btn:hover { color:#f87171; }

        .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">
            <a href="project-management.php" style="color:#c4b5fd; text-decoration:none; float:left;">
                ← Back to Projects
            </a>
            <h1><i class="fas fa-edit"></i> Edit Project</h1>
            <p><?= htmlspecialchars($project['project_code']) ?> — <?= htmlspecialchars($project['project_name']) ?></p>
        </div>

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

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

                <!-- Basic Fields -->
                <div class="form-group">
                    <label>Project Code</label>
                    <input type="text" value="<?= htmlspecialchars($project['project_code']) ?>" readonly>
                </div>

                <div class="form-group">
                    <label>Project Name <span style="color:#f87171;">*</span></label>
                    <input type="text" name="project_name" value="<?= htmlspecialchars($project['project_name']) ?>" required>
                </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="Ongoing" <?= $project['project_status'] === 'Ongoing' ? 'selected' : '' ?>>Planning</option>
                        <option value="In Progress" <?= $project['project_status'] === 'In Progress' ? 'selected' : '' ?>>In Progress</option>
                        <option value="Completed" <?= $project['project_status'] === 'Completed' ? 'selected' : '' ?>>Completed</option>
                        <option value="On Hold" <?= $project['project_status'] === 'On Hold' ? 'selected' : '' ?>>On Hold</option>
                        <option value="Cancelled" <?= $project['project_status'] === 'Cancelled' ? 'selected' : '' ?>>Cancelled</option>
                        <option value="Active" <?= $project['project_status'] === 'Active' ? 'selected' : '' ?>>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" value="<?= htmlspecialchars($project['client_name'] ?? '') ?>">
                    </div>
                    <div class="form-group"><label>GST Number</label>
                        <input type="text" name="gst_number" value="<?= htmlspecialchars($project['gst_number'] ?? '') ?>">
                    </div>
                </div>

                <div class="form-group">
                    <label>Project Address</label>
                    <input type="text" name="project_address" value="<?= htmlspecialchars($project['project_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" value="<?= $project['start_date'] ?? '' ?>"></div>
                    <div class="form-group"><label>End Date</label><input type="date" name="end_date" value="<?= $project['end_date'] ?? '' ?>"></div>
                    <div class="form-group"><label>Contract Value (₹)</label><input type="number" name="project_contract_value" step="0.01" value="<?= $project['project_contract_value'] ?? '' ?>"></div>
                    <div class="form-group"><label>Budget (₹)</label><input type="number" name="project_budget" step="0.01" value="<?= $project['project_budget'] ?? '' ?>"></div>
                </div>

                <!-- 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 
                        mysqli_data_seek($managers_result, 0);
                        while ($m = $managers_result->fetch_assoc()): 
                            $checked = in_array($m['id'], $assigned_managers) ? 'checked' : '';
                        ?>
                            <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'] ?>" <?= $checked ?>>
                                <label for="pm<?= $m['id'] ?>"><?= htmlspecialchars($m['full_name']) ?></label>
                            </div>
                        <?php endwhile; ?>
                    </div>
                </div>

                <!-- 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()">+ Add Milestone</button>

                <!-- Existing Attachments with Delete Option -->
                <?php if (!empty($attachments)): ?>
                <div class="section-title"><i class="fas fa-paperclip"></i> Existing Attachments</div>
                <div style="margin-bottom:25px;">
                    <?php foreach ($attachments as $att): ?>
                    <div class="file-item">
                        <div>
                            <i class="fas fa-file"></i> 
                            <a href="../<?= htmlspecialchars($att['file_path']) ?>" target="_blank" style="color:#c4b5fd;">
                                <?= htmlspecialchars($att['original_name']) ?>
                            </a>
                        </div>
                        <div>
                            <small><?= number_format($att['file_size']/1024, 1) ?> KB</small>
                            <a href="edit-project.php?id=<?= $project_id ?>&delete_attachment=<?= $att['id'] ?>" 
                               class="delete-btn" 
                               onclick="return confirm('Delete this attachment?')">
                                <i class="fas fa-trash"></i>
                            </a>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>

                <!-- Add New Attachments -->
                <div class="section-title"><i class="fas fa-plus"></i> Add New Attachments</div>
                <div class="attachment-area" id="dropZone">
                    <i class="fas fa-cloud-upload-alt" style="font-size:3.5rem; opacity:0.7;"></i>
                    <p><strong>Drop files here</strong> or click to browse</p>
                    <small>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-save"></i> Update Project
                </button>
            </form>
        </div>
    </div>
</div>

<script>
// Load Existing Milestones
function loadExistingMilestones() {
    <?php foreach ($milestones as $ms): ?>
        addMilestoneRow(
            "<?= addslashes($ms['milestone_name']) ?>",
            "<?= $ms['amount'] ?>",
            "<?= $ms['due_date'] ?? '' ?>"
        );
    <?php endforeach; ?>
    if (<?= count($milestones) ?> === 0) addMilestoneRow();
}

function addMilestoneRow(name = '', amount = '', date = '') {
    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. 40% Completion"></div>
        <div><label>Amount (₹)</label><input type="number" name="milestone_amount[]" value="${amount}" step="0.01"></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);
}

// File Upload
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 div = document.createElement('div');
        div.className = 'file-item';
        div.innerHTML = `<span><i class="fas fa-file"></i> ${file.name}</span><small>${(file.size/1024/1024).toFixed(2)} MB</small>`;
        fileList.appendChild(div);
    });
}

window.onload = loadExistingMilestones;
</script>
</body>
</html>

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