<?php
session_start();
require_once 'db.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: signin');
    exit();
}

// Verify role-based access
checkAccess();

$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'] ?? 'User';
$user_email = $_SESSION['user_email'] ?? '';
$user_role = $_SESSION['user_role'] ?? 'Designer';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $client_name = trim($_POST['clientName']);
        $business_category = $_POST['businessCategory'];
        $contact_person = trim($_POST['contactPerson'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $address = trim($_POST['address'] ?? '');

        $project_name = trim($_POST['projectName']);
        $project_type = $_POST['projectType'];
        $project_address = trim($_POST['projectAddress']);
        $city = trim($_POST['city']);
        $state = $_POST['state'];
        $project_scope = trim($_POST['projectScope']);
        $project_estimate = floatval($_POST['projectEstimate']);
        $project_area = floatval($_POST['projectArea']);
        $created_date = $_POST['createdDate'];
        $recce_due_date = $_POST['recceDueDate'];
        $start_date = $_POST['startDate'];
        $execution_date = $_POST['executionDate'];
        $project_status = $_POST['projectStatus'] ?? 'Planning';

        // Backend Validation
        if (empty($client_name)) throw new Exception("Client Name is required.");
        if (empty($phone)) throw new Exception("Phone Number is required.");
        
        if (!preg_match('/^[0-9\-\+\s]{10,15}$/', $phone)) {
            throw new Exception("Please provide a valid phone number (10-15 digits).");
        }

        $project_id = $_POST['projectId'] ?? '';
        $client_id = $_POST['clientId'] ?? '';
        
        // Document Upload Handling
        $document_file_name = $_POST['existing_document'] ?? null;

        $master_designer_id = isset($_POST['masterDesignerId']) && $_POST['masterDesignerId'] !== '' ? (int)$_POST['masterDesignerId'] : null;

        if (isset($_FILES['document_file']) && $_FILES['document_file']['error'] === UPLOAD_ERR_OK) {
            $file_tmp = $_FILES['document_file']['tmp_name'];
            $original_name = $_FILES['document_file']['name'];
            $file_ext = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
            $allowed_exts = ['pdf', 'doc', 'docx'];

            if (in_array($file_ext, $allowed_exts)) {
                $upload_dir = 'uploads/projectsuploads/';
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0755, true);
                }

                // Create a unique name
                $new_file_name = time() . '_' . preg_replace("/[^a-zA-Z0-9.]/", "_", $original_name);
                $target_path = $upload_dir . $new_file_name;

                if (move_uploaded_file($file_tmp, $target_path)) {
                    // Delete old file if updating
                    $old_file = basename($_POST['existing_document']);
                    if (!empty($old_file) && file_exists($upload_dir . $old_file)) {
                        unlink($upload_dir . $old_file);
                    }
                    $document_file_name = $new_file_name;
                }
            }
        }

        if (empty($project_id)) {
            // Create new client and project
            mysqli_begin_transaction($conn);

            // Insert client
            $stmt = mysqli_prepare($conn, "INSERT INTO clients (client_name, business_category, contact_person, phone, email, address, created_by_user_id) VALUES (?, ?, ?, ?, ?, ?, ?)");
            if (!$stmt) {
                throw new Exception("Prepare failed: " . mysqli_error($conn));
            }
            mysqli_stmt_bind_param($stmt, "ssssssi", $client_name, $business_category, $contact_person, $phone, $email, $address, $user_id);
            if (!mysqli_stmt_execute($stmt)) {
                throw new Exception("Execute failed: " . mysqli_stmt_error($stmt));
            }
            $client_id = mysqli_insert_id($conn);
            mysqli_stmt_close($stmt);

            // Insert project
            $stmt = mysqli_prepare($conn, "
                INSERT INTO projects (client_id, project_name, project_type, project_address, city, state, project_scope,
                                    project_estimate, project_area, created_date, recce_due_date, start_date, execution_date, status, document_file, created_by_user_id, master_designer_id)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");

            if (!$stmt) {
                throw new Exception("Prepare failed: " . mysqli_error($conn));
            }
            mysqli_stmt_bind_param($stmt, "issssssddsssssssi", $client_id, $project_name, $project_type, $project_address, $city, $state, $project_scope,
                          $project_estimate, $project_area, $created_date, $recce_due_date, $start_date, $execution_date, $project_status, $document_file_name, $user_id, $master_designer_id);

            if (!mysqli_stmt_execute($stmt)) {
                throw new Exception("Execute failed: " . mysqli_stmt_error($stmt));
            }
            mysqli_stmt_close($stmt);

            mysqli_commit($conn);
            $success_message = "Client and project created successfully!";

        } else {
            // Update existing project
            mysqli_begin_transaction($conn);

            $stmt = mysqli_prepare($conn, "
                UPDATE projects SET project_name=?, project_type=?, project_address=?, city=?, state=?,
                                   project_scope=?, project_estimate=?, project_area=?, created_date=?,
                                   recce_due_date=?, start_date=?, execution_date=?, status=?, document_file=?, master_designer_id=?
                WHERE id=?
            ");

            if (!$stmt) {
                throw new Exception("Prepare failed: " . mysqli_error($conn));
            }
            mysqli_stmt_bind_param($stmt, "ssssssddssssssii", $project_name, $project_type, $project_address, $city, $state, $project_scope,
                          $project_estimate, $project_area, $created_date, $recce_due_date, $start_date,
                          $execution_date, $project_status, $document_file_name, $master_designer_id, $project_id);

            if (!mysqli_stmt_execute($stmt)) {
                throw new Exception("Execute failed: " . mysqli_stmt_error($stmt));
            }
            mysqli_stmt_close($stmt);

            // Update client info
            $stmt = mysqli_prepare($conn, "UPDATE clients SET client_name=?, business_category=?, contact_person=?, phone=?, email=?, address=? WHERE id=?");
            if (!$stmt) {
                throw new Exception("Prepare failed: " . mysqli_error($conn));
            }
            mysqli_stmt_bind_param($stmt, "ssssssi", $client_name, $business_category, $contact_person, $phone, $email, $address, $client_id);
            if (!mysqli_stmt_execute($stmt)) {
                throw new Exception("Execute failed: " . mysqli_stmt_error($stmt));
            }
            mysqli_stmt_close($stmt);

            mysqli_commit($conn);
            $success_message = "Project updated successfully!";
        }

    } catch (Exception $e) {
        if (isset($conn)) {
            mysqli_rollback($conn);
        }
        $error_message = "Error: " . $e->getMessage();
    }
}



// Fetch recent projects
$recent_projects = [];
try {
    $stmt = mysqli_prepare($conn, "
        SELECT p.*, c.client_name, c.business_category
        FROM projects p
        JOIN clients c ON p.client_id = c.id
        ORDER BY p.created_at DESC
        LIMIT 10
    ");
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $recent_projects = mysqli_fetch_all($result, MYSQLI_ASSOC);
    mysqli_stmt_close($stmt);

} catch (Exception $e) {
    // Handle error silently
}

// Handle project deletion
if (isset($_POST['action']) && $_POST['action'] === 'delete_project' && isset($_POST['project_id'])) {
    try {
        $project_id = $_POST['project_id'];

        // Check if project belongs to user
        $stmt = mysqli_prepare($conn, "
            SELECT p.id, p.document_file FROM projects p
            JOIN clients c ON p.client_id = c.id
            WHERE p.id = ?
        ");
        mysqli_stmt_bind_param($stmt, "i", $project_id);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        $project = mysqli_fetch_assoc($result);
        mysqli_stmt_close($stmt);

        if (!$project) {
            $error_message = "Project not found or access denied";
        } else {
            // Delete associated document file if exists
            if (!empty($project['document_file'])) {
                $file_to_delete = 'uploads/projectsuploads/' . $project['document_file'];
                if (file_exists($file_to_delete)) {
                    unlink($file_to_delete);
                }
            }

            // Delete project
            $stmt = mysqli_prepare($conn, "DELETE FROM projects WHERE id = ?");
            mysqli_stmt_bind_param($stmt, "i", $project_id);
            if (!mysqli_stmt_execute($stmt)) {
                throw new Exception("Delete failed: " . mysqli_stmt_error($stmt));
            }
            mysqli_stmt_close($stmt);

            $success_message = "Project deleted successfully!";
        }

    } catch (Exception $e) {
        $error_message = "Error: " . $e->getMessage();
    }
}

// Handle project search
$search_query = isset($_GET['search']) ? trim($_GET['search']) : '';

// Fetch recent projects with search
$recent_projects = [];

// Fetch designers for Master Designer dropdown
$designers = [];
try {
$stmt = mysqli_prepare($conn, "SELECT id, name FROM users WHERE role = 'Designer' ORDER BY name ASC");

    if ($stmt) {
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        $designers = mysqli_fetch_all($result, MYSQLI_ASSOC);
        mysqli_stmt_close($stmt);
    }
} catch (Exception $e) {
    // Handle silently
}
try {

    if (empty($search_query)) {
        $stmt = mysqli_prepare($conn, "
            SELECT p.*, c.client_name, c.business_category
            FROM projects p
            JOIN clients c ON p.client_id = c.id
            ORDER BY p.created_at DESC
            LIMIT 10
        ");
    } else {
        $search_term = "%$search_query%";
        $stmt = mysqli_prepare($conn, "
            SELECT p.*, c.client_name, c.business_category
            FROM projects p
            JOIN clients c ON p.client_id = c.id
            WHERE (p.project_name LIKE ? OR c.client_name LIKE ?)
            ORDER BY p.created_at DESC
            LIMIT 10
        ");
        mysqli_stmt_bind_param($stmt, "ss", $search_term, $search_term);
    }

    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $recent_projects = mysqli_fetch_all($result, MYSQLI_ASSOC);
    mysqli_stmt_close($stmt);

} catch (Exception $e) {
    // Handle error silently
}

// Handle AJAX search request
if (isset($_GET['action']) && $_GET['action'] === 'search_projects') {
    header('Content-Type: application/json');

    try {
        $query = isset($_GET['query']) ? trim($_GET['query']) : '';

        if (empty($query)) {
            // Return recent projects
            $stmt = mysqli_prepare($conn, "
                SELECT p.*, c.client_name, c.business_category
                FROM projects p
                JOIN clients c ON p.client_id = c.id
                ORDER BY p.created_at DESC
                LIMIT 10
            ");
        } else {
            // Search projects
            $search_term = "%$query%";
            $stmt = mysqli_prepare($conn, "
                SELECT p.*, c.client_name, c.business_category
                FROM projects p
                JOIN clients c ON p.client_id = c.id
                WHERE (p.project_name LIKE ? OR c.client_name LIKE ?)
                ORDER BY p.created_at DESC
                LIMIT 10
            ");
            mysqli_stmt_bind_param($stmt, "ss", $search_term, $search_term);
        }

        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        $projects = mysqli_fetch_all($result, MYSQLI_ASSOC);
        mysqli_stmt_close($stmt);

        echo json_encode(['success' => true, 'projects' => $projects]);

    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }

    exit();
}

// Handle project selection for editing
if (isset($_GET['project_id']) && isset($_GET['client_id'])) {
    try {
        $project_id = $_GET['project_id'];
        $client_id = $_GET['client_id'];

$stmt = mysqli_prepare($conn, "
            SELECT p.*, c.id as client_id, c.client_name, c.business_category, c.contact_person, c.phone, c.email, c.address, c.created_at as client_created_at
            FROM projects p
            JOIN clients c ON p.client_id = c.id
            WHERE p.id = ? AND c.id = ?
        ");


        mysqli_stmt_bind_param($stmt, "ii", $project_id, $client_id);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        $selected_project = mysqli_fetch_assoc($result);
        mysqli_stmt_close($stmt);

    } catch (Exception $e) {
        // Handle error silently
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Project Dashboard - ConstructCRM</title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <style>
    :root {
        --primary-color: #977C49;
        --primary-dark: #7a633a;
        --primary-light: #f8f5ef;
        --secondary-color: #343a40;
        --secondary-light: #f8f9fa;
        --success-color: #28a745;
        --info-color: #17a2b8;
        --warning-color: #ffc107;
        --danger-color: #dc3545;
        --light-color: #f8f9fa;
        --dark-color: #343a40;
        --sidebar-width: 320px;
        --nav-width: 260px;
        --header-height: 70px;
        --footer-height: 40px;
        --border-radius: 8px;
        --box-shadow: 0 4px 6px rgba(0, 0, 0, 0.07);
        --transition: all 0.3s ease;
    }

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: 'Inter', sans-serif;
        background-color: #f5f7fa;
        color: #333;
        font-size: 14px;
        line-height: 1.4;
        overflow-x: hidden;
    }

    /* Header */
    .header {
        background-color: #fff;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        height: var(--header-height);
        z-index: 1000;
        display: flex;
        align-items: center;
        padding: 0 20px;
    }

    .logo {
        display: flex;
        align-items: center;
        font-weight: 700;
        font-size: 20px;
        color: var(--primary-color);
            text-decoration: none;
    }

    .logo i {
        font-size: 24px;
        margin-right: 10px;
    }

    .header-actions {
        margin-left: auto;
        display: flex;
        align-items: center;
    }

    .mobile-menu-toggle {
        display: none;
        background: none;
        border: none;
        font-size: 24px;
        color: var(--primary-color);
        margin-right: 15px;
        cursor: pointer;
    }

    /* User Dropdown */
    .user-dropdown {
        position: relative;
    }

    .user-profile {
        display: flex;
        align-items: center;
        cursor: pointer;
        padding: 5px 10px;
        border-radius: var(--border-radius);
        transition: var(--transition);
    }

    .user-profile:hover {
        background-color: #f8f9fa;
    }

    .user-avatar {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background-color: var(--primary-color);
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        margin-right: 10px;
    }

    .user-name {
        font-weight: 500;
        margin-right: 5px;
    }

    .dropdown-arrow {
        font-size: 12px;
        color: #666;
        transition: var(--transition);
    }

    .user-dropdown.show .dropdown-arrow {
        transform: rotate(180deg);
    }

    .user-dropdown-menu {
        position: absolute;
        top: 100%;
        right: 0;
        background-color: #fff;
        border-radius: var(--border-radius);
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        min-width: 180px;
        padding: 8px 0;
        margin-top: 5px;
        opacity: 0;
        visibility: hidden;
        transform: translateY(-10px);
        transition: var(--transition);
        z-index: 1001;
    }

    .user-dropdown.show .user-dropdown-menu {
        opacity: 1;
        visibility: visible;
        transform: translateY(0);
    }

    .dropdown-item {
        display: flex;
        align-items: center;
        padding: 10px 20px;
        color: #555;
        text-decoration: none;
        transition: var(--transition);
    }

    .dropdown-item:hover {
        background-color: #f8f9fa;
        color: var(--primary-color);
    }

    .dropdown-item i {
        margin-right: 10px;
        font-size: 16px;
    }

    .dropdown-divider {
        height: 1px;
        background-color: #eee;
        margin: 8px 0;
    }

    /* Main Layout */
    .main-container {
        display: flex;
        min-height: calc(100vh - var(--header-height));
        margin-top: var(--header-height);
    }

    /* Sidebar Navigation */
    .sidebar-nav {
        width: var(--nav-width);
        background-color: #fff;
        box-shadow: 2px 0 10px rgba(0, 0, 0, 0.05);
        position: fixed;
        top: var(--header-height);
        left: 0;
        bottom: 0;
        z-index: 999;
        overflow-y: auto;
        transition: var(--transition);
    }

    .nav-section {
        padding: 15px 0;
    }

    .nav-section:last-child {
        padding-bottom: 20px;
    }

    .nav-title {
        font-size: 11px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: #999;
        padding: 0 20px;
        margin-bottom: 10px;
    }

    .nav-list {
        list-style: none;
    }

    .nav-item {
        margin-bottom: 5px;
    }

    .nav-link {
        display: flex;
        align-items: center;
        padding: 12px 20px;
        color: #555;
        text-decoration: none;
        font-weight: 500;
        transition: var(--transition);
        position: relative;
    }

    .nav-link i {
        font-size: 18px;
        margin-right: 12px;
        width: 20px;
        text-align: center;
    }

    .nav-link:hover {
        background-color: rgba(151, 124, 73, 0.05);
        color: var(--primary-color);
    }

    .nav-link.active {
        background-color: rgba(151, 124, 73, 0.1);
        color: var(--primary-color);
    }

    .nav-link.active::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        width: 4px;
        background-color: var(--primary-color);
    }

    /* Content Wrapper */
    .content-wrapper {
        flex: 1;
        margin-left: var(--nav-width);
        display: flex;
        flex-direction: column;
        transition: var(--transition);
    }

    .content-header {
        background-color: #fff;
        padding: 20px 30px;
        border-bottom: 1px solid #eee;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .page-title {
        font-size: 24px;
        font-weight: 600;
        color: #333;
    }

    .breadcrumb {
        background-color: transparent;
        padding: 0;
        margin: 0;
        font-size: 13px;
    }

    .breadcrumb-item {
        color: #999;
    }

    /* Fix for breadcrumb links */
    .breadcrumb-item a {
        color: #999;
        text-decoration: none;
        transition: var(--transition);
    }

    .breadcrumb-item a:hover {
        color: var(--primary-color);
    }

    .breadcrumb-item.active {
        color: var(--primary-color);
    }

    .breadcrumb-item + .breadcrumb-item::before {
        content: "›";
        color: #ccc;
    }

    /* Main Content */
    .main-content {
        flex: 1;
        display: flex;
        padding: 30px;
        gap: 30px;
    }

    /* Form Container */
    .form-container {
        flex: 1;
        background-color: #fff;
        border-radius: var(--border-radius);
        box-shadow: var(--box-shadow);
        overflow: hidden;
    }

    .form-header {
        background-color: var(--primary-color);
        color: white;
        padding: 20px 30px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .form-title {
        font-size: 18px;
        font-weight: 600;
        margin: 0;
    }

    .form-body {
        padding: 30px;
    }

    .form-section {
        margin-bottom: 30px;
    }

    .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #eee;
        display: flex;
        align-items: center;
    }

    .section-title i {
        color: var(--primary-color);
        margin-right: 10px;
    }

    .form-group {
        margin-bottom: 20px;
    }

    .form-label {
        font-weight: 500;
        color: #555;
        margin-bottom: 8px;
        font-size: 14px;
    }

    .form-control, .form-select {
        border: 1px solid #ddd;
        border-radius: var(--border-radius);
        padding: 10px 15px;
        font-size: 14px;
        transition: var(--transition);
    }

    .form-control:focus, .form-select:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 3px rgba(151, 124, 73, 0.2);
        outline: none;
    }

    .input-group-text {
        background-color: #f8f9fa;
        border: 1px solid #ddd;
        color: #666;
    }

    .btn {
        border-radius: var(--border-radius);
        font-weight: 500;
        padding: 10px 20px;
        font-size: 14px;
        transition: var(--transition);
        cursor: pointer;
    }

    .btn-primary {
        background-color: var(--primary-color);
        border-color: var(--primary-color);
    }

    .btn-primary:hover {
        background-color: var(--primary-dark);
        border-color: var(--primary-dark);
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(151, 124, 73, 0.3);
    }

    .btn-outline-primary {
        color: var(--primary-color);
        border-color: var(--primary-color);
    }

    .btn-outline-primary:hover {
        background-color: var(--primary-color);
        border-color: var(--primary-color);
        color: white;
    }

    .btn-outline-secondary {
        border-color: #ddd;
        color: #666;
    }

    .btn-outline-secondary:hover {
        background-color: #f8f9fa;
        border-color: #ccc;
        color: #555;
    }

    /* Project Sidebar */
    .project-sidebar {
        width: var(--sidebar-width);
        background-color: #fff;
        border-radius: var(--border-radius);
        box-shadow: var(--box-shadow);
        display: flex;
        flex-direction: column;
        overflow: hidden;
    }

    .sidebar-header {
        padding: 20px;
        border-bottom: 1px solid #eee;
    }

    .sidebar-title {
        font-size: 18px;
        font-weight: 600;
        margin-bottom: 15px;
        color: #333;
    }

    .project-list {
        flex: 1;
        overflow-y: auto;
        padding: 10px;
    }

    .project-item {
        padding: 15px;
        margin-bottom: 10px;
        border-radius: var(--border-radius);
        border: 1px solid #eee;
        cursor: pointer;
        transition: var(--transition);
    }

    .project-item:hover {
        border-color: var(--primary-color);
        box-shadow: 0 3px 6px rgba(0, 0, 0, 0.08);
    }

    .project-item.active {
        background-color: rgba(151, 124, 73, 0.1);
        border-color: var(--primary-color);
    }

    .project-client {
        font-weight: 600;
        color: #333;
        margin-bottom: 5px;
    }

    .project-name {
        font-size: 13px;
        color: #666;
    }

    .project-meta {
        display: flex;
        justify-content: space-between;
        margin-top: 10px;
        font-size: 12px;
        color: #999;
    }

    .project-status {
        padding: 3px 8px;
        border-radius: 12px;
        font-size: 11px;
        font-weight: 500;
        background-color: #f0f0f0;
    }

    .status-planning {
        background-color: #e3f2fd;
        color: #1976d2;
    }

    .status-active {
        background-color: #e8f5e9;
        color: #388e3c;
    }

    .status-completed {
        background-color: #f3e5f5;
        color: #7b1fa2;
    }
    
    .status-on-hold {
        background-color: #fff3e0;
        color: #f57c00;
    }
    
    .status-cancelled {
        background-color: #ffebee;
        color: #d32f2f;
    }

    /* Alert */
    .alert {
        border-radius: var(--border-radius);
        padding: 15px 20px;
        margin-bottom: 20px;
        border: none;
    }

    .alert-success {
        background-color: rgba(40, 167, 69, 0.1);
        color: var(--success-color);
    }

    .alert-info {
        background-color: rgba(23, 162, 184, 0.1);
        color: var(--info-color);
    }

    .alert-danger {
        background-color: rgba(220, 53, 69, 0.1);
        color: var(--danger-color);
    }

    /* Form Actions */
    .form-actions {
        display: flex;
        justify-content: center;
        gap: 15px;
        margin-top: 30px;
        padding-top: 20px;
        border-top: 1px solid #eee;
    }

    /* Responsive */
    @media (max-width: 1200px) {
        .project-sidebar {
            width: 280px;
        }
    }

    @media (max-width: 992px) {
        .main-content {
            flex-direction: column;
        }
        
        .project-sidebar {
            width: 100%;
            max-height: 400px;
        }
    }

    @media (max-width: 768px) {
        .mobile-menu-toggle {
            display: block;
        }
        
        .sidebar-nav {
            transform: translateX(-100%);
            width: 280px;
            z-index: 1001;
        }
        
        .sidebar-nav.show {
            transform: translateX(0);
        }
        
        .content-wrapper {
            margin-left: 0;
        }

        .overlay {
            z-index: 1000;
        }

        .overlay.show {
            display: block;
        }
        
        .form-container {
            margin-bottom: 30px;
        }

        .content-header {
            padding: 15px 20px;
            flex-direction: column;
            align-items: flex-start;
        }

        .page-title {
            font-size: 20px;
            margin-bottom: 10px;
        }

        .main-content {
            padding: 20px;
        }

        .form-body {
            padding: 20px;
        }

        .header {
            padding: 0 15px;
        }

        .logo {
            font-size: 18px;
        }

        .logo i {
            font-size: 20px;
        }

        .user-name {
            display: none;
        }

        .user-avatar {
            width: 32px;
            height: 32px;
            font-size: 14px;
        }
    }

    /* Additional styling */
    .empty-state {
        text-align: center;
        padding: 40px 20px;
        color: #999;
    }

    .empty-state i {
        font-size: 48px;
        margin-bottom: 15px;
        color: #ddd;
    }

    .empty-state p {
        margin: 0;
    }

    /* Loading spinner */
    .spinner {
        display: inline-block;
        width: 20px;
        height: 20px;
        border: 3px solid rgba(151, 124, 73, 0.3);
        border-radius: 50%;
        border-top-color: var(--primary-color);
        animation: spin 1s ease-in-out infinite;
    }

    @keyframes spin {
        to { transform: rotate(360deg); }
    }

    /* Custom scrollbar */
    ::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }

    ::-webkit-scrollbar-track {
        background: #f1f1f1;
    }

    ::-webkit-scrollbar-thumb {
        background: #ddd;
        border-radius: 4px;
    }

    ::-webkit-scrollbar-thumb:hover {
        background: #ccc;
    }

    /* Overlay for mobile menu */
    .overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 998;
    }

    .overlay.show {
        display: block;
    }
    </style>
</head>
<body>
    <!-- Header -->
    <header class="header">
        <button class="mobile-menu-toggle" id="mobileMenuToggle">
            <i class="bi bi-list"></i>
        </button>
        <a href="crmdashboard" class="logo">
            <img src="./assets/logo.png" alt="ConstructCRM Logo" style="height: 60px; width: 85px;">
        </a>
        <div class="header-actions">
            <!-- User Dropdown -->
            <div class="user-dropdown" id="userDropdown">
                <div class="user-profile" id="userProfile">
                    <div class="user-avatar"><?php echo strtoupper(substr($user_name, 0, 1)); ?></div>
                    <span class="user-name"><?php echo htmlspecialchars($user_name); ?></span>
                    <i class="bi bi-chevron-down dropdown-arrow"></i>
                </div>
                <div class="user-dropdown-menu">
                    <a href="profile" class="dropdown-item">
                        <i class="bi bi-person"></i>
                        <span>Profile</span>
                    </a>
                    <a href="settings" class="dropdown-item">
                        <i class="bi bi-gear"></i>
                        <span>Settings</span>
                    </a>
                    <div class="dropdown-divider"></div>
                    <a href="signin?logout=true" class="dropdown-item">
                        <i class="bi bi-box-arrow-right"></i>
                        <span>Logout</span>
                    </a>
                </div>
            </div>
        </div>
    </header>

    <div class="main-container">
        <!-- Overlay for mobile -->
        <div class="overlay" id="overlay"></div>

        <!-- Sidebar Navigation -->
        <nav class="sidebar-nav" id="sidebarNav">
            <div class="nav-section">
                <div class="nav-title">Main</div>
                <ul class="nav-list">
                    <?php if (($_SESSION['user_role'] ?? '') === 'Admin'): ?>
                    <li class="nav-item">
                        <a href="crmdashboard" class="nav-link">
                            <i class="bi bi-speedometer2"></i>
                            <span>Dashboard</span>
                        </a>
                    </li>
                    <?php endif; ?>
                    <li class="nav-item">
                        <a href="dashboard" class="nav-link active">
                            <i class="bi bi-grid-1x2-fill"></i>
                            <span>Client</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="projectlist" class="nav-link">
                            <i class="bi bi-list-ul"></i>
                            <span>Project List</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="designimages" class="nav-link">
                            <i class="bi bi-palette-fill"></i>
                            <span>Design images</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="assignmentcalendar" class="nav-link">
                            <i class="bi bi-calendar-event-fill"></i>
                            <span>Assignment Calendar</span>
                        </a>
                    </li>
                    <?php if (($_SESSION['user_role'] ?? '') === 'Admin'): ?>
                    <li class="nav-item">
                        <a href="<?= BASE_URL ?>place_order" class="nav-link">
                            <i class="bi bi-cart-check"></i> 
                            <span>Place Order</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="financetracker" class="nav-link">
                            <i class="bi bi-cash-stack"></i>
                            <span>Finance Tracker</span>
                        </a>
                    </li>
                    <?php endif; ?>
                    <li class="nav-item">
                        <a href="imagepin" class="nav-link">
                            <i class="bi bi-pin-map-fill"></i>
                            <span>Image Pin & Comment</span>
                        </a>
                    </li>
                    <?php if (($_SESSION['user_role'] ?? '') === 'Admin'): ?>
                    <li class="nav-item">
                        <a href="designcost" class="nav-link">
                            <i class="bi bi-palette-fill"></i>
                            <span>Designs Cost</span>
                        </a>
                    </li>
                    <?php endif; ?>
                </ul>
            </div>
            
            <div class="nav-section">
                <div class="nav-title">Management</div>
                <ul class="nav-list">
                    <li class="nav-item">
                        <a href="taskmanager" class="nav-link">
                            <i class="bi bi-check2-square"></i>
                            <span>Task Manager</span>
                        </a>
                    </li>
                    <?php if (($_SESSION['user_role'] ?? '') === 'Admin'): ?>
                    <li class="nav-item">
                        <a href="users" class="nav-link">
                            <i class="bi bi-people-fill"></i>
                            <span>Users</span>
                        </a>
                    </li>
                    <?php endif; ?>
                </ul>
            </div>
            
            <?php if (($_SESSION['user_role'] ?? '') === 'Admin'): ?>
            <div class="nav-section">
                <div class="nav-title">Vendor Management</div>
                <ul class="nav-list">
                    <li class="nav-item">
                        <a href="addvendors" class="nav-link">
                            <i class="bi bi-person-plus-fill"></i>
                            <span>Add New Vendor</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="viewvendors" class="nav-link">
                            <i class="bi bi-card-list"></i>
                            <span>View All Vendors</span>
                        </a>
                    </li>
                </ul>
            </div>
            <?php endif; ?>
        </nav>

        <!-- Content Wrapper -->
        <div class="content-wrapper">
            <!-- Content Header -->
            <div class="content-header">
                <h1 class="page-title">Project Management</h1>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="#">Home</a></li>
                        <li class="breadcrumb-item"><a href="#">Management</a></li>
                        <li class="breadcrumb-item active" aria-current="page">Dashboard</li>
                    </ol>
                </nav>
            </div>

            <!-- Main Content -->
            <div class="main-content">
                <!-- Form Container -->
                <div class="form-container">
                    <div class="form-header">
                        <h4 class="form-title" id="form-title">
                            <i class="bi bi-<?php echo isset($selected_project) ? 'pencil-square' : 'plus-circle-fill'; ?>"></i> 
                            <?php echo isset($selected_project) ? 'Update Project' : 'Add New Client & Project'; ?>
                        </h4>
                    </div>
                    <div class="form-body">
                        <?php if (isset($success_message)): ?>
                        <div class="alert alert-success" role="alert">
                            <i class="bi bi-check-circle"></i> <?php echo htmlspecialchars($success_message); ?>
                        </div>
                        <?php endif; ?>
                        
                        <?php if (isset($error_message)): ?>
                        <div class="alert alert-danger" role="alert">
                            <i class="bi bi-exclamation-triangle"></i> <?php echo htmlspecialchars($error_message); ?>
                        </div>
                        <?php endif; ?>
                        
                        <div id="form-message" class="alert" role="alert" style="display: none;">
                        </div>

                        <form id="projectForm" class="needs-validation" method="POST" action="dashboard" enctype="multipart/form-data" novalidate>
                            <input type="hidden" id="projectId" name="projectId" value="<?php echo isset($selected_project) ? htmlspecialchars($selected_project['id']) : ''; ?>">
                            <input type="hidden" id="clientId" name="clientId" value="<?php echo isset($selected_project) ? htmlspecialchars($selected_project['client_id']) : ''; ?>">
                            
                            <div class="form-section">
                                <h5 class="section-title">
                                    <i class="bi bi-person-badge"></i> Client Information
                                </h5>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="clientName" class="form-label">Client Name</label>
                                            <input type="text" class="form-control" id="clientName" name="clientName" placeholder="e.g., Om Interior Studio" value="<?php echo isset($selected_project) ? htmlspecialchars($selected_project['client_name']) : ''; ?>" required>
                                            <div class="invalid-feedback">Please enter client's name.</div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="businessCategory" class="form-label">Business Category</label>
                                            <select class="form-select" id="businessCategory" name="businessCategory" required>
                                                <option value="" <?php echo !isset($selected_project) ? 'selected disabled' : 'disabled'; ?>>Select a category...</option>
                                                <option value="Residential" <?php echo (isset($selected_project) && $selected_project['business_category'] == 'Residential') ? 'selected' : ''; ?>>Residential</option>
                                                <option value="Commercial" <?php echo (isset($selected_project) && $selected_project['business_category'] == 'Commercial') ? 'selected' : ''; ?>>Commercial</option>
                                                <option value="Industrial" <?php echo (isset($selected_project) && $selected_project['business_category'] == 'Industrial') ? 'selected' : ''; ?>>Industrial</option>
                                                <option value="Renovation" <?php echo (isset($selected_project) && $selected_project['business_category'] == 'Renovation') ? 'selected' : ''; ?>>Renovation Specialist</option>
                                                <option value="Infrastructure" <?php echo (isset($selected_project) && $selected_project['business_category'] == 'Infrastructure') ? 'selected' : ''; ?>>Infrastructure</option>
                                            </select>
                                            <div class="invalid-feedback">Please select a business category.</div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="contactPerson" class="form-label">Contact Person</label>
                                            <input type="text" class="form-control" id="contactPerson" name="contactPerson" placeholder="e.g., Sarah Smith" value="<?php echo isset($selected_project) ? htmlspecialchars($selected_project['contact_person']) : ''; ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="phone" class="form-label">Phone Number</label>
                                            <input type="tel" class="form-control" id="phone" name="phone" placeholder="e.g., 98765XXXXX" value="<?php echo isset($selected_project) ? htmlspecialchars($selected_project['phone']) : ''; ?>" required>
                                            <div class="invalid-feedback">Please enter a valid phone number.</div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="email" class="form-label">Email Address</label>
                                            <input type="email" class="form-control" id="email" name="email" placeholder="e.g., client@example.com" value="<?php echo isset($selected_project) ? htmlspecialchars($selected_project['email']) : ''; ?>">
                                            <div class="invalid-feedback">Please enter a valid email address.</div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="address" class="form-label">Client Address</label>
                                            <input type="text" class="form-control" id="address" name="address" placeholder="e.g., 123 Business Way" value="<?php echo isset($selected_project) ? htmlspecialchars($selected_project['address']) : ''; ?>">
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="form-section">
                                <h5 class="section-title">
                                    <i class="bi bi-building"></i> Project Information
                                </h5>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <label for="masterDesignerId" class="form-label">Master Designer</label>
                                            <select class="form-select" id="masterDesignerId" name="masterDesignerId">
                                                <option value="" <?php echo (!isset($selected_project) || empty($selected_project['master_designer_id'])) ? 'selected' : ''; ?>>Select Master Designer...</option>
                                                <?php if (!empty($designers)): ?>
                                                    <?php foreach ($designers as $d): ?>
                                                        <option value="<?php echo (int)$d['id']; ?>" <?php echo (isset($selected_project) && (int)$selected_project['master_designer_id'] === (int)$d['id']) ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($d['name']); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="projectName" class="form-label">Project Name</label>
                                            <input type="text" class="form-control" id="projectName" name="projectName" placeholder="e.g., Sunrise Apartments" value="<?php echo isset($selected_project) ? htmlspecialchars($selected_project['project_name']) : ''; ?>" required>
                                            <div class="invalid-feedback">Please provide a project name.</div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="projectType" class="form-label">Project Type</label>
                                            <select class="form-select" id="projectType" name="projectType" required>
                                                <option value="" <?php echo !isset($selected_project) ? 'selected disabled' : 'disabled'; ?>>Select a type...</option>
                                                <option value="New Construction" <?php echo (isset($selected_project) && $selected_project['project_type'] == 'New Construction') ? 'selected' : ''; ?>>New Construction</option>
                                                <option value="Remodeling / Renovation" <?php echo (isset($selected_project) && $selected_project['project_type'] == 'Remodeling / Renovation') ? 'selected' : ''; ?>>Remodeling / Renovation</option>
                                                <option value="Home/Building Addition" <?php echo (isset($selected_project) && $selected_project['project_type'] == 'Home/Building Addition') ? 'selected' : ''; ?>>Home/Building Addition</option>
                                                <option value="Site Development" <?php echo (isset($selected_project) && $selected_project['project_type'] == 'Site Development') ? 'selected' : ''; ?>>Site Development</option>
                                                <option value="Interior Fit-out" <?php echo (isset($selected_project) && $selected_project['project_type'] == 'Interior Fit-out') ? 'selected' : ''; ?>>Interior Fit-out</option>
                                            </select>
                                            <div class="invalid-feedback">Please select a project type.</div>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="projectAddress" class="form-label">Project Address</label>
                                    <textarea class="form-control" id="projectAddress" name="projectAddress" rows="3" placeholder="Enter full site address" required><?php echo isset($selected_project) ? htmlspecialchars($selected_project['project_address']) : ''; ?></textarea>
                                    <div class="invalid-feedback">Please enter the project address.</div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="city" class="form-label">City</label>
                                            <input type="text" class="form-control" id="city" name="city" value="<?php echo isset($selected_project) ? htmlspecialchars($selected_project['city']) : ''; ?>" required>
                                            <div class="invalid-feedback">Please enter the city.</div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="state" class="form-label">State</label>
                                            <select class="form-select" id="state" name="state" required>
                                                <option value="" <?php echo !isset($selected_project) ? 'selected disabled' : 'disabled'; ?>>Select a state...</option>
                                                <option value="Gujarat" <?php echo (isset($selected_project) && $selected_project['state'] == 'Gujarat') ? 'selected' : ''; ?>>Gujarat</option>
                                                <option value="Maharashtra" <?php echo (isset($selected_project) && $selected_project['state'] == 'Maharashtra') ? 'selected' : ''; ?>>Maharashtra</option>
                                                <option value="Rajasthan" <?php echo (isset($selected_project) && $selected_project['state'] == 'Rajasthan') ? 'selected' : ''; ?>>Rajasthan</option>
                                                <option value="Delhi" <?php echo (isset($selected_project) && $selected_project['state'] == 'Delhi') ? 'selected' : ''; ?>>Delhi</option>
                                                <option value="Karnataka" <?php echo (isset($selected_project) && $selected_project['state'] == 'Karnataka') ? 'selected' : ''; ?>>Karnataka</option>
                                            </select>
                                            <div class="invalid-feedback">Please select a state.</div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="form-section">
                                <h5 class="section-title">
                                    <i class="bi bi-clipboard-data"></i> Project Scope & Estimates
                                </h5>

                                <div class="form-group">
                                    <label for="projectScope" class="form-label">Project Scope</label>
                                    <textarea class="form-control" id="projectScope" name="projectScope" rows="3" placeholder="Describe the scope of work, key deliverables, and objectives..." required><?php echo isset($selected_project) ? htmlspecialchars($selected_project['project_scope']) : ''; ?></textarea>
                                    <div class="invalid-feedback">Please describe the project scope.</div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="projectEstimate" class="form-label">Client Budget (INR)</label>
                                            <div class="input-group">
                                                <span class="input-group-text">₹</span>
                                                <input type="number" class="form-control" id="projectEstimate" name="projectEstimate" placeholder="e.g., 500000" value="<?php echo isset($selected_project) ? htmlspecialchars($selected_project['project_estimate']) : ''; ?>" required>
                                                <div class="invalid-feedback">Please enter an Client Budget.</div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="projectArea" class="form-label">Project Area (SQFT)</label>
                                            <div class="input-group">
                                                <input type="number" class="form-control" id="projectArea" name="projectArea" placeholder="e.g., 1200" value="<?php echo isset($selected_project) ? htmlspecialchars($selected_project['project_area']) : ''; ?>" required>
                                                <span class="input-group-text">SQFT</span>
                                                <div class="invalid-feedback">Please enter the total area.</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="form-section">
                                <h5 class="section-title">
                                    <i class="bi bi-calendar3"></i> Important Dates
                                </h5>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="createdDate" class="form-label">Project Created Date</label>
                                            <input type="date" class="form-control" id="createdDate" name="createdDate" value="<?php echo isset($selected_project) ? htmlspecialchars($selected_project['created_date']) : ''; ?>" required>
                                            <div class="invalid-feedback">Please select the creation date.</div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="recceDueDate" class="form-label">Office Visit Date</label>
                                            <input type="date" class="form-control" id="recceDueDate" name="recceDueDate" value="<?php echo isset($selected_project) ? htmlspecialchars($selected_project['recce_due_date']) : ''; ?>" required>
                                            <div class="invalid-feedback">Please select the Office Visit date.</div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="startDate" class="form-label">Expected Start Date</label>
                                            <input type="date" class="form-control" id="startDate" name="startDate" value="<?php echo isset($selected_project) ? htmlspecialchars($selected_project['start_date']) : ''; ?>" required>
                                            <div class="invalid-feedback">Please select the expected start date.</div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="executionDate" class="form-label">Execution Date</label>
                                            <input type="date" class="form-control" id="executionDate" name="executionDate" value="<?php echo isset($selected_project) ? htmlspecialchars($selected_project['execution_date']) : ''; ?>" required>
                                            <div class="invalid-feedback">Please select the execution date.</div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="form-section">
                                <h5 class="section-title">
                                    <i class="bi bi-flag"></i> Project Status
                                </h5>
                                <div class="form-group">
                                    <label for="projectStatus" class="form-label">Current Status</label>
                                    <select class="form-select" id="projectStatus" name="projectStatus">
                                        <option value="Planning" <?php echo (isset($selected_project) && $selected_project['status'] == 'Planning') ? 'selected' : ''; ?>>Planning</option>
                                        <option value="Active" <?php echo (isset($selected_project) && $selected_project['status'] == 'Active') ? 'selected' : ''; ?>>Active</option>
                                        <option value="Completed" <?php echo (isset($selected_project) && $selected_project['status'] == 'Completed') ? 'selected' : ''; ?>>Completed</option>
                                        <option value="On Hold" <?php echo (isset($selected_project) && $selected_project['status'] == 'On Hold') ? 'selected' : ''; ?>>On Hold</option>
                                        <option value="Cancelled" <?php echo (isset($selected_project) && $selected_project['status'] == 'Cancelled') ? 'selected' : ''; ?>>Cancelled</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-section">
                                <h5 class="section-title">
                                    <i class="bi bi-paperclip"></i> Documents & Attachments
                                </h5>
                                <div id="attachments-list" class="mb-3">
                                    <?php if (isset($selected_project['document_file']) && $selected_project['document_file']): ?>
                                        <div class="alert alert-info d-flex align-items-center justify-content-between">
                                            <span>
                                                <i class="bi bi-file-earmark-check me-2"></i>
                                                Current: <a href="uploads/projectsuploads/<?php echo $selected_project['document_file']; ?>" target="_blank" class="text-decoration-none fw-bold"><?php echo htmlspecialchars($selected_project['document_file']); ?></a>
                                            </span>
                                            <input type="hidden" name="existing_document" value="<?php echo $selected_project['document_file']; ?>">
                                        </div>
                                    <?php endif; ?>
                                    <div id="selected-file-info" class="text-muted small mt-2"></div>
                                </div>
                                <input type="file" id="document_file" name="document_file" accept=".pdf,.doc,.docx" style="display: none;">
                                <button type="button" id="add-attachment-btn" class="btn btn-outline-primary">
                                    <i class="bi bi-file-earmark-arrow-up me-2"></i>
                                    <span id="btn-text"><?php echo isset($selected_project['document_file']) ? 'Change Document' : 'Add New Document'; ?></span>
                                </button>
                            </div>

                            <div class="form-actions">
                                <button class="btn btn-primary" type="submit" id="saveBtn">
                                    <i class="bi bi-<?php echo isset($selected_project) ? 'pencil-square' : 'check-circle'; ?>"></i> 
                                    <?php echo isset($selected_project) ? 'Update Project' : 'Save Project'; ?>
                                </button>
                                <button class="btn btn-outline-secondary" type="button" id="clearBtn">
                                    <i class="bi bi-x-circle"></i> Clear Form
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Project Sidebar -->
                <div class="project-sidebar">
                    <div class="sidebar-header">
                        <h5 class="sidebar-title">Recent Projects</h5>
                        <div class="search-container" style="margin-bottom: 15px;">
                            <div class="input-group">
                                <span class="input-group-text"><i class="bi bi-search"></i></span>
                                <input type="text" class="form-control" id="projectSearch" placeholder="Search projects..." value="<?php echo htmlspecialchars($search_query); ?>" style="font-size: 14px;">
                            </div>
                        </div>
                        <a href="dashboard" class="btn btn-primary">
                            <i class="bi bi-plus-lg"></i> Add New Project
                        </a>
                    </div>
                    <div class="project-list">
                        <?php if (empty($recent_projects)): ?>
                        <div class="empty-state">
                            <i class="bi bi-inbox"></i>
                            <p><?php echo empty($search_query) ? 'No projects yet.' : 'No projects found matching your search.'; ?></p>
                        </div>
                        <?php else: ?>
                            <?php foreach ($recent_projects as $project): ?>
                            <div class="project-item <?php echo (isset($selected_project) && $selected_project['id'] == $project['id']) ? 'active' : ''; ?>">
                                <a href="dashboard?project_id=<?php echo $project['id']; ?>&client_id=<?php echo $project['client_id']; ?>&search=<?php echo urlencode($search_query); ?>" class="project-link" style="text-decoration: none; color: inherit; display: block;">
                                    <div class="project-client"><?php echo htmlspecialchars($project['client_name']); ?></div>
                                    <div class="project-name"><?php echo htmlspecialchars($project['project_name']); ?></div>
                                    <div class="project-meta">
                                        <span class="project-status status-<?php echo strtolower(str_replace(' ', '-', $project['status'] ?? 'planning')); ?>">
                                            <?php echo htmlspecialchars($project['status'] ?? 'Planning'); ?>
                                        </span>
                                        <span><?php echo date('M d, Y', strtotime($project['created_at'])); ?></span>
                                    </div>
                                </a>
                                <form method="POST" action="dashboard" style="display: inline;" onsubmit="return confirm('Are you sure you want to delete this project? This action cannot be undone.');">
                                    <input type="hidden" name="action" value="delete_project">
                                    <input type="hidden" name="project_id" value="<?php echo $project['id']; ?>">
                                    <button type="submit" class="btn btn-sm btn-outline-danger delete-project-btn" title="Delete Project" style="position: absolute; top: 10px; right: 10px;">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </form>
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

    <script>
        // JavaScript for UI interactions and search functionality
        document.addEventListener('DOMContentLoaded', function () {
            // Bootstrap form validation
            const forms = document.querySelectorAll('.needs-validation')
            Array.from(forms).forEach(form => {
                form.addEventListener('submit', event => {
                    if (!form.checkValidity()) {
                        event.preventDefault()
                        event.stopPropagation()
                    }
                    form.classList.add('was-validated')
                }, false)
            })

            // Mobile menu toggle
            const mobileMenuToggle = document.getElementById('mobileMenuToggle');
            const sidebarNav = document.getElementById('sidebarNav');
            const overlay = document.getElementById('overlay');

            if (mobileMenuToggle && sidebarNav && overlay) {
                mobileMenuToggle.addEventListener('click', () => {
                    sidebarNav.classList.toggle('show');
                    overlay.classList.toggle('show');
                });

                overlay.addEventListener('click', () => {
                    sidebarNav.classList.remove('show');
                    overlay.classList.remove('show');
                });

                // Close sidebar when clicking a nav link on mobile
                document.querySelectorAll('.nav-link').forEach(link => {
                    link.addEventListener('click', () => {
                        if (window.innerWidth <= 768) {
                            sidebarNav.classList.remove('show');
                            overlay.classList.remove('show');
                        }
                    });
                });
            }

            // Document Upload Trigger
            const addDocBtn = document.getElementById('add-attachment-btn');
            const docInput = document.getElementById('document_file');
            const fileInfo = document.getElementById('selected-file-info');

            if (addDocBtn && docInput) {
                addDocBtn.addEventListener('click', () => docInput.click());
                
                docInput.addEventListener('change', function() {
                    if (this.files && this.files[0]) {
                        fileInfo.innerHTML = `<i class="bi bi-check-lg text-success"></i> Selected: <strong>${this.files[0].name}</strong>`;
                    }
                });
            }

            // User dropdown toggle
            const userDropdown = document.getElementById('userDropdown');
            const userProfile = document.getElementById('userProfile');

            if (userDropdown && userProfile) {
                userProfile.addEventListener('click', (e) => {
                    e.stopPropagation();
                    userDropdown.classList.toggle('show');
                });

                // Close dropdown when clicking outside
                document.addEventListener('click', () => {
                    userDropdown.classList.remove('show');
                });
            }

            // Set default date on initial load
            const createdDateInput = document.getElementById('createdDate');
            if (createdDateInput && !createdDateInput.value) {
                const today = new Date().toISOString().split('T')[0];
                createdDateInput.value = today;
            }

            // Search functionality
            const projectSearch = document.getElementById('projectSearch');
            let searchTimeout;

            if (projectSearch) {
                projectSearch.addEventListener('input', (e) => {
                    clearTimeout(searchTimeout);
                    const query = e.target.value.trim();

                    searchTimeout = setTimeout(() => {
                        searchProjects(query);
                    }, 300); // Debounce search by 300ms
                });
            }

            async function searchProjects(query) {
                try {
                    const response = await fetch(`dashboard?action=search_projects&query=${encodeURIComponent(query)}`);
                    const data = await response.json();

                    if (data.success) {
                        updateProjectList(data.projects);
                    } else {
                        console.error('Search failed:', data.message);
                    }
                } catch (error) {
                    console.error('Search error:', error);
                }
            }

            function updateProjectList(projects) {
                const projectList = document.querySelector('.project-list');
                if (!projectList) return;

                projectList.innerHTML = '';

                if (projects.length === 0) {
                    projectList.innerHTML = `
                        <div class="empty-state">
                            <i class="bi bi-inbox"></i>
                            <p>No projects found matching your search.</p>
                        </div>
                    `;
                    return;
                }

                projects.forEach(project => {
                    const projectItem = document.createElement('div');
                    projectItem.className = 'project-item';
                    projectItem.innerHTML = `
                        <a href="dashboard?project_id=${project.id}&client_id=${project.client_id}&search=${encodeURIComponent(projectSearch.value)}" class="project-link" style="text-decoration: none; color: inherit; display: block;">
                            <div class="project-client">${project.client_name}</div>
                            <div class="project-name">${project.project_name}</div>
                            <div class="project-meta">
                                <span class="project-status status-${(project.status || 'planning').toLowerCase().replace(' ', '-')}">
                                    ${project.status || 'Planning'}
                                </span>
                                <span>${new Date(project.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</span>
                            </div>
                        </a>
                        <form method="POST" action="dashboard" style="display: inline;" onsubmit="return confirm('Are you sure you want to delete this project? This action cannot be undone.');">
                            <input type="hidden" name="action" value="delete_project">
                            <input type="hidden" name="project_id" value="${project.id}">
                            <button type="submit" class="btn btn-sm btn-outline-danger delete-project-btn" title="Delete Project" style="position: absolute; top: 10px; right: 10px;">
                                <i class="bi bi-trash"></i>
                            </button>
                        </form>
                    `;
                    projectList.appendChild(projectItem);
                });
            }
        });
    </script>
</body>
</html>