<?php
session_start();
require_once dirname(__DIR__) . '/includes/functions.php';

billing_require_auth();
billing_ensure_project_support();

$user = billing_current_user();
$organization = billing_current_organization();

if (!$user) {
    billing_redirect('signin.php');
}

if (!$organization || empty($organization['onboarding_completed_at'])) {
    billing_redirect('onboarding.php?step=1');
}

$userId = (int) $user['id'];
$organizationId = (int) $organization['id'];
$projects = billing_get_projects($userId, $organizationId);
$customers = billing_get_customers($userId);
$billingMethods = billing_project_billing_methods();

if (!isset($_SESSION['projects_timer']) || !is_array($_SESSION['projects_timer'])) {
    $_SESSION['projects_timer'] = [];
}
if (!isset($_SESSION['projects_custom_fields']) || !is_array($_SESSION['projects_custom_fields'])) {
    $_SESSION['projects_custom_fields'] = [];
}
if (!isset($_SESSION['projects_custom_buttons']) || !is_array($_SESSION['projects_custom_buttons'])) {
    $_SESSION['projects_custom_buttons'] = [];
}
if (!isset($_SESSION['projects_related_lists']) || !is_array($_SESSION['projects_related_lists'])) {
    $_SESSION['projects_related_lists'] = [];
}

$timerState = $_SESSION['projects_timer'];
$customFields = $_SESSION['projects_custom_fields'];
$customButtons = $_SESSION['projects_custom_buttons'];
$relatedLists = $_SESSION['projects_related_lists'];

$sortColumn = strtolower(trim((string) ($_GET['sort'] ?? 'created_time')));
$sortOrder = strtolower(trim((string) ($_GET['order'] ?? 'desc')));
$allowedSortColumns = ['created_time', 'last_modified_time', 'customer_name', 'project_name', 'rate'];
if (!in_array($sortColumn, $allowedSortColumns, true)) {
    $sortColumn = 'created_time';
}
if (!in_array($sortOrder, ['asc', 'desc'], true)) {
    $sortOrder = 'desc';
}

usort($projects, static function (array $left, array $right) use ($sortColumn, $sortOrder): int {
    if ($sortColumn === 'customer_name') {
        $result = strcasecmp((string) ($left['customer_name'] ?? ''), (string) ($right['customer_name'] ?? ''));
    } elseif ($sortColumn === 'project_name') {
        $result = strcasecmp((string) ($left['project_name'] ?? ''), (string) ($right['project_name'] ?? ''));
    } elseif ($sortColumn === 'rate') {
        $result = ((float) ($left['billing_rate'] ?? 0)) <=> ((float) ($right['billing_rate'] ?? 0));
    } elseif ($sortColumn === 'last_modified_time') {
        $result = strcmp((string) ($left['created_at'] ?? ''), (string) ($right['created_at'] ?? ''));
    } else {
        $result = strcmp((string) ($left['created_at'] ?? ''), (string) ($right['created_at'] ?? ''));
    }

    return $sortOrder === 'asc' ? $result : ($result * -1);
});

$view = isset($_GET['view']) && $_GET['view'] === 'cards' ? 'cards' : 'list';
$showNewProject = isset($_GET['new']) && $_GET['new'] === '1';
$showTimerModal = isset($_GET['timer']) && $_GET['timer'] === '1';
$activeSettingsTab = strtolower(trim((string) ($_GET['settings'] ?? '')));
$activeSettingsTab = in_array($activeSettingsTab, ['fields', 'buttons', 'related'], true) ? $activeSettingsTab : '';
$showNewCustomField = $activeSettingsTab === 'fields' && isset($_GET['new_field']) && $_GET['new_field'] === '1';
$timerTaskMode = isset($_GET['task_mode']) && $_GET['task_mode'] === 'create' ? 'create' : 'select';
$projectErrors = [];
$timerErrors = [];
$customFieldErrors = [];
$timerFlash = billing_flash('projects_timer_success');
$timerErrorFlash = billing_flash('projects_timer_error');
$projectsSuccess = billing_flash('projects_success');
$projectsError = billing_flash('projects_error');

$projectFieldTypeOptions = [
    'text_single' => 'Text Box (Single Line)',
    'email' => 'Email',
    'url' => 'URL',
    'phone' => 'Phone',
    'number' => 'Number',
    'decimal' => 'Decimal',
    'amount' => 'Amount',
    'date' => 'Date',
    'dropdown' => 'Dropdown',
];

$customFieldForm = [
    'label_name' => '',
    'data_type' => '',
    'help_text' => '',
    'is_mandatory' => '0',
    'contains_pii' => '0',
    'contains_ephi' => '0',
    'prevent_duplicates' => '0',
    'input_format' => '',
    'default_value' => '',
];

$timerForm = [
    'project_id' => '',
    'project_name' => '',
    'task_name' => '',
    'billable' => '1',
    'notes' => '',
];

$defaultUserLabel = (string) ($user['business_name'] ?? $organization['organization_name'] ?? $user['email'] ?? 'User');
$defaultUserEmail = (string) ($user['email'] ?? '');

$formData = [
    'project_name' => '',
    'project_code' => '',
    'customer_name' => '',
    'billing_method' => 'project_hours',
    'description_text' => '',
    'cost_budget' => '',
    'revenue_budget' => '',
    'watchlist_enabled' => '1',
    'users' => [[
        'display_name' => $defaultUserLabel,
        'email' => $defaultUserEmail,
        'role_label' => 'Admin',
    ]],
    'tasks' => [[
        'task_name' => 'Task Name',
        'description_text' => 'Description',
        'is_billable' => '1',
    ]],
];

$buildProjectsUrl = static function (array $params = []) use (&$view, &$activeSettingsTab, &$showNewProject, &$showTimerModal, &$showNewCustomField, &$timerTaskMode, &$sortColumn, &$sortOrder): string {
    $query = [];

    if ($view === 'cards') {
        $query['view'] = 'cards';
    }
    if ($showNewProject) {
        $query['new'] = '1';
    }
    if ($showTimerModal) {
        $query['timer'] = '1';
    }
    if ($activeSettingsTab !== '') {
        $query['settings'] = $activeSettingsTab;
    }
    if ($showNewCustomField) {
        $query['new_field'] = '1';
    }
    if ($timerTaskMode === 'create') {
        $query['task_mode'] = 'create';
    }
    if ($sortColumn !== 'created_time') {
        $query['sort'] = $sortColumn;
    }
    if ($sortOrder !== 'desc') {
        $query['order'] = $sortOrder;
    }

    $query = array_merge($query, $params);
    foreach ($query as $key => $value) {
        if ($value === null || $value === '' || $value === false) {
            unset($query[$key]);
        }
    }

    return 'projects.php' . ($query !== [] ? '?' . http_build_query($query) : '');
};

$projectOptionsById = [];
foreach ($projects as $project) {
    $projectId = (int) ($project['id'] ?? 0);
    if ($projectId <= 0) {
        continue;
    }

    $tasks = [];
    foreach ((array) ($project['tasks'] ?? []) as $task) {
        $taskName = trim((string) ($task['task_name'] ?? ''));
        if ($taskName !== '') {
            $tasks[] = [
                'id' => (int) ($task['id'] ?? 0),
                'name' => $taskName,
                'billable' => !empty($task['is_billable']),
            ];
        }
    }

    $projectOptionsById[$projectId] = [
        'id' => $projectId,
        'name' => (string) ($project['project_name'] ?? ''),
        'customer_name' => (string) ($project['customer_name'] ?? ''),
        'tasks' => $tasks,
    ];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string) ($_POST['action'] ?? '') === 'create_project') {
    $showNewProject = true;
    $formData['project_name'] = trim((string) ($_POST['project_name'] ?? ''));
    $formData['project_code'] = trim((string) ($_POST['project_code'] ?? ''));
    $formData['customer_name'] = trim((string) ($_POST['customer_name'] ?? ''));
    $formData['billing_method'] = trim((string) ($_POST['billing_method'] ?? 'project_hours'));
    $formData['description_text'] = trim((string) ($_POST['description_text'] ?? ''));
    $formData['cost_budget'] = trim((string) ($_POST['cost_budget'] ?? ''));
    $formData['revenue_budget'] = trim((string) ($_POST['revenue_budget'] ?? ''));
    $formData['watchlist_enabled'] = !empty($_POST['watchlist_enabled']) ? '1' : '';

    $rawUsers = is_array($_POST['users'] ?? null) ? $_POST['users'] : [];
    $rawTasks = is_array($_POST['tasks'] ?? null) ? $_POST['tasks'] : [];

    $formData['users'] = [];
    foreach ($rawUsers as $row) {
        $formData['users'][] = [
            'display_name' => trim((string) ($row['display_name'] ?? '')),
            'email' => trim((string) ($row['email'] ?? '')),
            'role_label' => trim((string) ($row['role_label'] ?? 'Admin')),
        ];
    }
    if ($formData['users'] === []) {
        $formData['users'][] = [
            'display_name' => $defaultUserLabel,
            'email' => $defaultUserEmail,
            'role_label' => 'Admin',
        ];
    }

    $formData['tasks'] = [];
    foreach ($rawTasks as $row) {
        $formData['tasks'][] = [
            'task_name' => trim((string) ($row['task_name'] ?? '')),
            'description_text' => trim((string) ($row['description_text'] ?? '')),
            'is_billable' => !empty($row['is_billable']) ? '1' : '',
        ];
    }
    if ($formData['tasks'] === []) {
        $formData['tasks'][] = [
            'task_name' => '',
            'description_text' => '',
            'is_billable' => '1',
        ];
    }

    if ($formData['project_name'] === '') {
        $projectErrors[] = 'Project name is required.';
    }
    if ($formData['customer_name'] === '') {
        $projectErrors[] = 'Customer name is required.';
    }

    if ($projectErrors === []) {
        $projectId = billing_save_project(
            $userId,
            $organizationId,
            [
                'project_name' => $formData['project_name'],
                'project_code' => $formData['project_code'],
                'customer_name' => $formData['customer_name'],
                'billing_method' => $formData['billing_method'],
                'billing_rate' => 0,
                'description_text' => $formData['description_text'],
                'cost_budget' => (float) ($formData['cost_budget'] !== '' ? $formData['cost_budget'] : 0),
                'revenue_budget' => (float) ($formData['revenue_budget'] !== '' ? $formData['revenue_budget'] : 0),
                'watchlist_enabled' => $formData['watchlist_enabled'] === '1' ? '1' : '',
                'users' => $formData['users'],
                'tasks' => $formData['tasks'],
            ]
        );

        if ($projectId !== null) {
            billing_redirect('projects.php?created=1');
        }

        $projectErrors[] = 'Project could not be saved.';
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string) ($_POST['action'] ?? '') === 'start_project_timer') {
    $showTimerModal = true;
    $timerForm['project_id'] = trim((string) ($_POST['project_id'] ?? ''));
    $timerForm['task_name'] = trim((string) ($_POST['task_name'] ?? ''));
    $timerForm['billable'] = !empty($_POST['billable']) ? '1' : '';
    $timerForm['notes'] = trim((string) ($_POST['notes'] ?? ''));
    $timerTaskMode = (string) ($_POST['task_mode'] ?? 'select') === 'create' ? 'create' : 'select';

    $selectedProjectId = (int) $timerForm['project_id'];
    $selectedProject = $projectOptionsById[$selectedProjectId] ?? null;
    if ($selectedProject !== null) {
        $timerForm['project_name'] = (string) ($selectedProject['name'] ?? '');
    }

    if ($selectedProjectId <= 0 || $selectedProject === null) {
        $timerErrors[] = 'Select a project to start the timer.';
    }

    if ($timerTaskMode === 'create') {
        if ($timerForm['task_name'] === '') {
            $timerErrors[] = 'Enter a task name or switch back to the task list.';
        }
    } elseif ($timerForm['task_name'] === '') {
        $timerErrors[] = 'Select a task or create a new one.';
    }

    if ($timerErrors === []) {
        $taskName = $timerForm['task_name'];
        $taskFound = false;
        foreach ((array) ($selectedProject['tasks'] ?? []) as $task) {
            if (strcasecmp((string) ($task['name'] ?? ''), $taskName) === 0) {
                $taskFound = true;
                $timerForm['billable'] = !empty($task['billable']) ? '1' : '';
                break;
            }
        }

        if (!$taskFound && $timerTaskMode === 'create' && $taskName !== '') {
            $conn = billing_db();
            $taskStmt = $conn->prepare(
                'INSERT INTO project_tasks (project_id, user_id, organization_id, task_name, description_text, is_billable)
                 VALUES (?, ?, ?, ?, "", ?)'
            );
            if ($taskStmt !== false) {
                $isBillableValue = $timerForm['billable'] === '1' ? 1 : 0;
                $taskStmt->bind_param('iiisi', $selectedProjectId, $userId, $organizationId, $taskName, $isBillableValue);
                $taskStmt->execute();
                $taskStmt->close();
            }
        }

        $_SESSION['projects_timer'] = [
            'project_id' => $selectedProjectId,
            'project_name' => (string) ($selectedProject['name'] ?? ''),
            'customer_name' => (string) ($selectedProject['customer_name'] ?? ''),
            'task_name' => $taskName,
            'notes' => $timerForm['notes'],
            'billable' => $timerForm['billable'] === '1',
            'started_at' => time(),
            'paused_at' => null,
            'elapsed_before_pause' => 0,
            'status' => 'running',
        ];

        billing_flash('projects_timer_success', 'Timer started.');
        billing_redirect($buildProjectsUrl(['timer' => null, 'task_mode' => null, 'new' => null]));
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string) ($_POST['action'] ?? '') === 'pause_project_timer') {
    $timerState = $_SESSION['projects_timer'] ?? [];
    if (($timerState['status'] ?? '') === 'running') {
        $startedAt = (int) ($timerState['started_at'] ?? time());
        $elapsedBeforePause = (int) ($timerState['elapsed_before_pause'] ?? 0);
        $timerState['elapsed_before_pause'] = $elapsedBeforePause + max(time() - $startedAt, 0);
        $timerState['paused_at'] = time();
        $timerState['status'] = 'paused';
        $_SESSION['projects_timer'] = $timerState;
    }
    billing_redirect($buildProjectsUrl(['timer' => null]));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string) ($_POST['action'] ?? '') === 'resume_project_timer') {
    $timerState = $_SESSION['projects_timer'] ?? [];
    if (($timerState['status'] ?? '') === 'paused') {
        $timerState['started_at'] = time();
        $timerState['paused_at'] = null;
        $timerState['status'] = 'running';
        $_SESSION['projects_timer'] = $timerState;
    }
    billing_redirect($buildProjectsUrl(['timer' => null]));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string) ($_POST['action'] ?? '') === 'stop_project_timer') {
    $timerState = $_SESSION['projects_timer'] ?? [];
    $projectId = (int) ($timerState['project_id'] ?? 0);
    if ($projectId > 0) {
        $elapsedSeconds = (int) ($timerState['elapsed_before_pause'] ?? 0);
        if (($timerState['status'] ?? '') === 'running') {
            $elapsedSeconds += max(time() - (int) ($timerState['started_at'] ?? time()), 0);
        }

        if ($elapsedSeconds > 0) {
            $entryId = billing_add_project_time_entry(
                $userId,
                $organizationId,
                [
                    'project_id' => $projectId,
                    'entry_date' => date('Y-m-d'),
                    'project_name' => (string) ($timerState['project_name'] ?? ''),
                    'customer_name' => (string) ($timerState['customer_name'] ?? ''),
                    'task_name' => (string) ($timerState['task_name'] ?? ''),
                    'user_display_name' => $defaultUserLabel,
                    'duration_seconds' => $elapsedSeconds,
                    'notes_text' => (string) ($timerState['notes'] ?? ''),
                    'billing_status' => !empty($timerState['billable']) ? 'Unbilled' : 'Non-Billable',
                ]
            );

            if ($entryId !== null) {
                billing_add_project_logged_time($userId, $organizationId, $projectId, $elapsedSeconds, !empty($timerState['billable']));
                billing_flash('projects_timer_success', 'Timer stopped and time entry saved.');
            } else {
                billing_flash('projects_timer_error', 'Timer stopped, but the time entry could not be saved.');
            }
        }
    }

    $_SESSION['projects_timer'] = [];
    billing_redirect($buildProjectsUrl(['timer' => null]));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string) ($_POST['action'] ?? '') === 'create_project_custom_field') {
    $activeSettingsTab = 'fields';
    $showNewCustomField = true;
    $customFieldForm['label_name'] = trim((string) ($_POST['label_name'] ?? ''));
    $customFieldForm['data_type'] = trim((string) ($_POST['data_type'] ?? ''));
    $customFieldForm['help_text'] = trim((string) ($_POST['help_text'] ?? ''));
    $customFieldForm['is_mandatory'] = !empty($_POST['is_mandatory']) ? '1' : '0';
    $customFieldForm['contains_pii'] = !empty($_POST['contains_pii']) ? '1' : '0';
    $customFieldForm['contains_ephi'] = !empty($_POST['contains_ephi']) ? '1' : '0';
    $customFieldForm['prevent_duplicates'] = !empty($_POST['prevent_duplicates']) ? '1' : '0';
    $customFieldForm['input_format'] = trim((string) ($_POST['input_format'] ?? ''));
    $customFieldForm['default_value'] = trim((string) ($_POST['default_value'] ?? ''));

    if ($customFieldForm['label_name'] === '') {
        $customFieldErrors[] = 'Label name is required.';
    }
    if ($customFieldForm['data_type'] === '' || !isset($projectFieldTypeOptions[$customFieldForm['data_type']])) {
        $customFieldErrors[] = 'Choose a valid data type.';
    }

    if ($customFieldErrors === []) {
        $_SESSION['projects_custom_fields'][] = [
            'label_name' => $customFieldForm['label_name'],
            'data_type' => $projectFieldTypeOptions[$customFieldForm['data_type']],
            'is_mandatory' => $customFieldForm['is_mandatory'] === '1',
            'help_text' => $customFieldForm['help_text'],
            'contains_pii' => $customFieldForm['contains_pii'] === '1',
            'contains_ephi' => $customFieldForm['contains_ephi'] === '1',
            'prevent_duplicates' => $customFieldForm['prevent_duplicates'] === '1',
            'input_format' => $customFieldForm['input_format'],
            'default_value' => $customFieldForm['default_value'],
            'status' => 'Active',
        ];
        billing_flash('projects_success', 'Custom field created successfully.');
        billing_redirect($buildProjectsUrl(['settings' => 'fields', 'new_field' => null]));
    }
}

$timerState = $_SESSION['projects_timer'] ?? [];
$customFields = $_SESSION['projects_custom_fields'] ?? [];
$customButtons = $_SESSION['projects_custom_buttons'] ?? [];
$relatedLists = $_SESSION['projects_related_lists'] ?? [];

$activeTimerSeconds = (int) ($timerState['elapsed_before_pause'] ?? 0);
if (($timerState['status'] ?? '') === 'running') {
    $activeTimerSeconds += max(time() - (int) ($timerState['started_at'] ?? time()), 0);
}

$billingActiveNav = 'projects';
$billingTopbarOrganizationName = (string) ($organization['organization_name'] ?? 'Billing');
$billingTopbarUserLabel = (string) ($user['email'] ?? '');

if (!function_exists('billing_projects_hours_label')) {
    function billing_projects_hours_label(int $seconds): string
    {
        $hours = intdiv(max(0, $seconds), 3600);
        $minutes = intdiv(max(0, $seconds) % 3600, 60);
        return sprintf('%02d:%02d', $hours, $minutes);
    }
}

if (!function_exists('billing_projects_timer_label')) {
    function billing_projects_timer_label(int $seconds): string
    {
        $seconds = max(0, $seconds);
        $hours = intdiv($seconds, 3600);
        $minutes = intdiv($seconds % 3600, 60);
        $remainingSeconds = $seconds % 60;
        return sprintf('%02dh : %02dm : %02ds', $hours, $minutes, $remainingSeconds);
    }
}

if (!function_exists('billing_projects_rate_label')) {
    function billing_projects_rate_label(array $project): string
    {
        $method = (string) ($project['billing_method'] ?? 'project_hours');
        $rate = (float) ($project['billing_rate'] ?? 0);
        return 'INR ' . number_format($rate, 2) . billing_project_rate_suffix($method);
    }
}

if (!function_exists('billing_projects_customer_options')) {
    function billing_projects_customer_options(array $customers): array
    {
        $options = [];
        foreach ($customers as $customer) {
            $name = trim((string) ($customer['customer_name'] ?? ''));
            if ($name !== '') {
                $options[] = $name;
            }
        }
        $options = array_values(array_unique($options));
        sort($options, SORT_NATURAL | SORT_FLAG_CASE);
        return $options;
    }
}

$customerOptions = billing_projects_customer_options($customers);
$customFieldsUsage = count($customFields);
$projectCustomFieldsPage = 'project_custom_fields.php';
$projectCustomButtonsPage = 'project_custom_buttons.php';
$projectRelatedListsPage = 'project_related_lists.php';
$projectCustomFieldNewPage = 'project_custom_field_new.php';

if ((string) ($_GET['export'] ?? '') !== '') {
    $exportMode = strtolower(trim((string) ($_GET['export'] ?? '')));
    if ($exportMode === 'tasks') {
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="project-tasks-' . date('Ymd-His') . '.csv"');
        echo "\"Project Name\",\"Task Name\",\"Billable\"\r\n";
        foreach ($projects as $project) {
            foreach ((array) ($project['tasks'] ?? []) as $task) {
                echo '"' . str_replace('"', '""', (string) ($project['project_name'] ?? '')) . '",';
                echo '"' . str_replace('"', '""', (string) ($task['task_name'] ?? '')) . '",';
                echo '"' . (!empty($task['is_billable']) ? 'Yes' : 'No') . "\"\r\n";
            }
        }
        exit;
    }

    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="projects-' . date('Ymd-His') . '.csv"');
    echo "\"Customer Name\",\"Project Name\",\"Billing Method\",\"Rate\",\"Logged Hours\"\r\n";
    foreach ($projects as $project) {
        echo '"' . str_replace('"', '""', (string) ($project['customer_name'] ?? '')) . '",';
        echo '"' . str_replace('"', '""', (string) ($project['project_name'] ?? '')) . '",';
        echo '"' . str_replace('"', '""', billing_project_billing_method_label((string) ($project['billing_method'] ?? 'project_hours'))) . '",';
        echo '"' . str_replace('"', '""', billing_projects_rate_label($project)) . '",';
        echo '"' . billing_projects_hours_label((int) ($project['logged_seconds'] ?? 0)) . "\"\r\n";
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="<?php echo billing_escape(billing_base_href()); ?>">
<title>Projects</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;700;800&display=swap">
<link rel="stylesheet" href="Payslip_Project/assets/fontawesome/css/all.min.css">
<link rel="stylesheet" href="assets/billing.css?v=20260507-project-views-restore">
<style>
.billing-projects-shell {
    position: relative;
}

.billing-projects-flash {
    margin: 18px 30px 0;
    padding: 14px 16px;
    border-radius: 12px;
    font-size: 14px;
    font-weight: 600;
}

.billing-projects-flash--success {
    background: #eaf8f0;
    color: #15803d;
}

.billing-projects-flash--error {
    background: #fff1f2;
    color: #be123c;
}

.billing-projects-action-cluster,
.billing-projects-split {
    position: relative;
}

.billing-projects-split {
    display: inline-flex;
}

.billing-projects-split .billing-projects-btn--green {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
}

.billing-projects-split-toggle {
    width: 36px;
    border-left: 1px solid rgba(255, 255, 255, 0.28);
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    padding: 0;
    justify-content: center;
}

.billing-projects-popover {
    position: absolute;
    top: calc(100% + 10px);
    right: 0;
    min-width: 176px;
    background: #fff;
    border: 1px solid #e4ebf5;
    border-radius: 14px;
    box-shadow: 0 12px 28px rgba(15, 23, 42, 0.12);
    z-index: 35;
    padding: 6px;
    display: none;
}

.billing-projects-popover.is-open {
    display: block;
}

.billing-projects-popover a,
.billing-projects-popover button {
    width: 100%;
    min-height: 44px;
    padding: 0 14px;
    border: 0;
    border-radius: 10px;
    background: transparent;
    color: #475467;
    text-decoration: none;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    font: inherit;
    font-size: 14px;
    cursor: pointer;
}

.billing-projects-popover a:hover,
.billing-projects-popover button:hover,
.billing-projects-popover a.is-active {
    background: #4785e8;
    color: #fff;
}

.billing-projects-popover .menu-copy {
    display: inline-flex;
    align-items: center;
    gap: 12px;
}

.billing-projects-popover-submenu {
    position: absolute;
    top: 0;
    right: calc(100% + 8px);
    min-width: 192px;
    background: #fff;
    border: 1px solid #e4ebf5;
    border-radius: 14px;
    box-shadow: 0 12px 28px rgba(15, 23, 42, 0.12);
    padding: 6px;
    display: none;
}

.billing-projects-menu-row {
    position: relative;
}

.billing-projects-menu-row.is-open > .billing-projects-popover-submenu {
    display: block;
}

.billing-projects-toolbar-timer {
    min-height: 40px;
    padding: 0 12px;
    border: 1px solid #dce5ef;
    border-radius: 10px;
    background: #f6f9ff;
    color: #0f1728;
    display: inline-flex;
    align-items: center;
    gap: 10px;
    font-weight: 700;
}

.billing-projects-toolbar-timer form {
    display: inline-flex;
}

.billing-projects-toolbar-mini {
    width: 40px;
    height: 40px;
    border: 0;
    border-left: 1px solid #dce5ef;
    background: transparent;
    color: #1f63e9;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

.billing-projects-timer-dock {
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 50;
    min-width: 275px;
    height: 52px;
    padding: 0 18px;
    background: #eef1f7;
    border-top: 1px solid #d6deea;
    border-right: 1px solid #d6deea;
    display: flex;
    align-items: center;
    gap: 16px;
}

.billing-projects-timer-dock strong {
    color: #0f1728;
    font-size: 17px;
}

.billing-projects-dock-actions {
    margin-left: auto;
    display: inline-flex;
    align-items: center;
    gap: 14px;
}

.billing-projects-dock-actions button {
    border: 0;
    background: transparent;
    color: #1f63e9;
    font-size: 20px;
    cursor: pointer;
}

.billing-projects-timer-overlay {
    position: fixed;
    inset: 0;
    z-index: 60;
    background: rgba(17, 24, 39, 0.56);
    display: grid;
    place-items: center;
    padding: 22px;
}

.billing-projects-timer-modal {
    width: min(625px, 100%);
    border-radius: 14px;
    background: #fff;
    overflow: hidden;
    box-shadow: 0 18px 40px rgba(15, 23, 42, 0.18);
}

.billing-projects-timer-head {
    position: relative;
    padding: 18px 28px 20px;
    border-bottom: 1px solid #eceff5;
    text-align: center;
}

.billing-projects-timer-head h2,
.billing-projects-timer-head strong,
.billing-projects-timer-head span {
    display: block;
}

.billing-projects-timer-head span {
    color: #475467;
    font-size: 14px;
    letter-spacing: 0.04em;
}

.billing-projects-timer-head h2 {
    margin: 8px 0 0;
    color: #111827;
    font-size: 22px;
    font-weight: 500;
}

.billing-projects-timer-head strong {
    margin-top: 4px;
    color: #1f2937;
    font-size: 28px;
}

.billing-projects-timer-close {
    position: absolute;
    top: 16px;
    right: 18px;
    color: #111827;
    text-decoration: none;
    font-size: 22px;
}

.billing-projects-timer-form {
    padding: 24px 24px 0;
}

.billing-projects-timer-errors {
    margin-bottom: 14px;
    padding: 12px 14px;
    border-radius: 12px;
    background: #fff1f2;
    color: #be123c;
    display: grid;
    gap: 6px;
}

.billing-projects-field {
    margin-bottom: 20px;
}

.billing-projects-field label,
.billing-projects-field .field-label {
    display: block;
    margin-bottom: 10px;
    color: #ef4444;
    font-size: 14px;
    font-weight: 500;
}

.billing-projects-field input[type="text"],
.billing-projects-field textarea,
.billing-projects-field select {
    width: 100%;
    min-height: 42px;
    padding: 0 14px;
    border: 1px solid #ced8ea;
    border-radius: 10px;
    font: inherit;
    color: #334155;
}

.billing-projects-field textarea {
    min-height: 40px;
    padding-top: 10px;
    resize: vertical;
}

.billing-projects-choice-panel {
    position: relative;
}

.billing-projects-choice-trigger {
    width: 100%;
    min-height: 44px;
    padding: 0 14px;
    border: 1px solid #ced8ea;
    border-radius: 10px;
    background: #fff;
    color: #98a2b3;
    display: flex;
    align-items: center;
    justify-content: space-between;
    text-align: left;
    font: inherit;
    cursor: pointer;
}

.billing-projects-choice-panel.is-open .billing-projects-choice-trigger {
    border-color: #4f8df5;
    box-shadow: 0 0 0 2px rgba(79, 141, 245, 0.15);
}

.billing-projects-choice-menu {
    margin-top: 10px;
    border: 1px solid #e1e8f2;
    border-radius: 12px;
    background: #fff;
    box-shadow: 0 12px 28px rgba(15, 23, 42, 0.12);
    overflow: hidden;
    display: none;
}

.billing-projects-choice-panel.is-open .billing-projects-choice-menu {
    display: block;
}

.billing-projects-choice-search {
    padding: 8px;
    border-bottom: 1px solid #edf1f6;
}

.billing-projects-choice-search input {
    width: 100%;
    min-height: 42px;
    padding: 0 14px;
    border: 1px solid #4f8df5;
    border-radius: 10px;
    font: inherit;
}

.billing-projects-choice-list {
    max-height: 180px;
    overflow: auto;
}

.billing-projects-choice-item,
.billing-projects-choice-empty,
.billing-projects-choice-footer {
    min-height: 48px;
    padding: 0 14px;
    display: flex;
    align-items: center;
}

.billing-projects-choice-item {
    width: 100%;
    border: 0;
    background: transparent;
    color: #475467;
    font: inherit;
    cursor: pointer;
}

.billing-projects-choice-item:hover,
.billing-projects-choice-item.is-selected {
    background: #4785e8;
    color: #fff;
}

.billing-projects-choice-empty {
    color: #667085;
}

.billing-projects-choice-footer {
    border-top: 1px solid #edf1f6;
}

.billing-projects-choice-footer button,
.billing-projects-task-mode-link {
    border: 0;
    background: transparent;
    color: #3b82f6;
    font: inherit;
    cursor: pointer;
    padding: 0;
}

.billing-projects-inline-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
}

.billing-projects-billable {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    color: #374151;
    font-size: 14px;
}

.billing-projects-timer-actions {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 18px 24px 28px;
    border-top: 1px solid #eceff5;
}

.billing-projects-settings-shell {
    background: #fff;
}

.billing-projects-settings-head {
    min-height: 88px;
    padding: 0 24px;
    border-bottom: 1px solid #e8edf5;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 18px;
}

.billing-projects-settings-head h2 {
    margin: 0;
    font-size: 23px;
}

.billing-projects-settings-tabs {
    display: flex;
    align-items: center;
    gap: 34px;
    padding: 0 24px;
    border-bottom: 1px solid #e8edf5;
}

.billing-projects-settings-tabs a {
    min-height: 54px;
    color: #56657c;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    border-bottom: 3px solid transparent;
    font-size: 15px;
    font-weight: 600;
}

.billing-projects-settings-tabs a.is-active {
    color: #17233b;
    border-bottom-color: #4785e8;
}

.billing-projects-settings-body {
    padding: 0 0 18px;
}

.billing-projects-settings-table {
    width: 100%;
    border-collapse: collapse;
}

.billing-projects-settings-table th,
.billing-projects-settings-table td {
    padding: 14px 18px;
    border-bottom: 1px solid #edf1f6;
    text-align: left;
}

.billing-projects-settings-table th {
    color: #677991;
    font-size: 13px;
    font-weight: 800;
}

.billing-projects-settings-empty {
    padding: 80px 24px;
    text-align: center;
    color: #667085;
}

.billing-projects-settings-empty strong {
    display: block;
    margin-bottom: 10px;
    color: #17233b;
    font-size: 18px;
}

.billing-projects-custom-field-form {
    padding: 18px 24px 26px;
}

.billing-projects-custom-field-grid {
    display: grid;
    grid-template-columns: 240px minmax(0, 420px);
    gap: 18px 36px;
    align-items: start;
}

.billing-projects-custom-field-grid .wide {
    grid-column: 1 / -1;
}

.billing-project-card-actions a,
.billing-project-card-actions button {
    min-height: 28px;
    padding: 0 10px;
    border: 1px solid #d7e2ef;
    border-radius: 6px;
    background: #fff;
    color: #17233b;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
}
</style>
</head>
<body class="billing-dashboard-page">
<div class="dashboard-shell">
    <?php include dirname(__DIR__) . '/includes/app_sidebar.php'; ?>
    <div class="dashboard-main">
        <?php include dirname(__DIR__) . '/includes/topbar.php'; ?>
        <main class="dashboard-content billing-projects-page">
            <section class="billing-projects-shell">
                <?php if ($projectsSuccess !== null): ?>
                    <div class="billing-projects-flash billing-projects-flash--success"><?php echo billing_escape($projectsSuccess); ?></div>
                <?php endif; ?>
                <?php if ($projectsError !== null): ?>
                    <div class="billing-projects-flash billing-projects-flash--error"><?php echo billing_escape($projectsError); ?></div>
                <?php endif; ?>
                <?php if ($timerFlash !== null): ?>
                    <div class="billing-projects-flash billing-projects-flash--success"><?php echo billing_escape($timerFlash); ?></div>
                <?php endif; ?>
                <?php if ($timerErrorFlash !== null): ?>
                    <div class="billing-projects-flash billing-projects-flash--error"><?php echo billing_escape($timerErrorFlash); ?></div>
                <?php endif; ?>

                <div class="billing-projects-head">
                    <div class="billing-projects-tabs">
                        <a class="is-active" href="<?php echo billing_escape($buildProjectsUrl(['settings' => null, 'new' => null, 'new_field' => null])); ?>">All Projects <i class="fa-solid fa-angle-down"></i></a>
                    </div>
                    <div class="billing-projects-actions">
                        <div class="billing-projects-view-toggle" aria-label="Project view toggle">
                            <a class="<?php echo $view === 'list' ? 'is-active' : ''; ?>" href="<?php echo billing_escape($buildProjectsUrl(['view' => null, 'settings' => null, 'new' => null, 'new_field' => null])); ?>"><i class="fa-solid fa-list"></i></a>
                            <a class="<?php echo $view === 'cards' ? 'is-active' : ''; ?>" href="<?php echo billing_escape($buildProjectsUrl(['view' => 'cards', 'settings' => null, 'new' => null, 'new_field' => null])); ?>"><i class="fa-regular fa-square"></i></a>
                        </div>

                        <?php if (($timerState['status'] ?? '') !== ''): ?>
                            <div class="billing-projects-toolbar-timer">
                                <i class="fa-regular fa-clock"></i>
                                <span id="billingProjectsToolbarTimer" data-running="<?php echo ($timerState['status'] ?? '') === 'running' ? '1' : '0'; ?>" data-elapsed="<?php echo $activeTimerSeconds; ?>" data-started="<?php echo (int) ($timerState['started_at'] ?? time()); ?>"><?php echo billing_escape(billing_projects_timer_label($activeTimerSeconds)); ?></span>
                                <?php if (($timerState['status'] ?? '') === 'running'): ?>
                                    <form method="post">
                                        <input type="hidden" name="action" value="pause_project_timer">
                                        <button class="billing-projects-toolbar-mini" type="submit" aria-label="Pause"><i class="fa-solid fa-pause"></i></button>
                                    </form>
                                <?php else: ?>
                                    <form method="post">
                                        <input type="hidden" name="action" value="resume_project_timer">
                                        <button class="billing-projects-toolbar-mini" type="submit" aria-label="Resume"><i class="fa-solid fa-play"></i></button>
                                    </form>
                                <?php endif; ?>
                                <form method="post">
                                    <input type="hidden" name="action" value="stop_project_timer">
                                    <button class="billing-projects-toolbar-mini" type="submit" aria-label="Stop"><i class="fa-regular fa-circle-stop"></i></button>
                                </form>
                            </div>
                        <?php else: ?>
                            <a class="billing-projects-btn" href="<?php echo billing_escape($buildProjectsUrl(['timer' => '1', 'new' => null, 'settings' => null, 'new_field' => null])); ?>"><i class="fa-regular fa-clock"></i> Start</a>
                        <?php endif; ?>

                        <div class="billing-projects-split">
                            <a class="billing-projects-btn billing-projects-btn--green" href="<?php echo billing_escape($buildProjectsUrl(['new' => '1', 'settings' => null, 'new_field' => null, 'timer' => null])); ?>"><i class="fa-solid fa-plus"></i> New</a>
                            <button class="billing-projects-btn billing-projects-btn--green billing-projects-split-toggle" type="button" data-popover-toggle="newMenu" aria-label="New menu"><i class="fa-solid fa-angle-down"></i></button>
                            <div class="billing-projects-popover" id="newMenu">
                                <a href="<?php echo billing_escape($buildProjectsUrl(['new' => '1', 'settings' => null, 'new_field' => null])); ?>"><span class="menu-copy"><i class="fa-solid fa-folder-plus"></i> New Project</span></a>
                                <a href="<?php echo billing_escape($buildProjectsUrl(['timer' => '1', 'task_mode' => 'create', 'settings' => null])); ?>"><span class="menu-copy"><i class="fa-regular fa-clock"></i> Log Time</span></a>
                            </div>
                        </div>

                        <div class="billing-projects-action-cluster">
                            <button class="billing-projects-icon-btn" type="button" aria-label="More actions" data-popover-toggle="moreProjectsMenu">
                                <i class="fa-solid fa-ellipsis"></i>
                            </button>
                            <div class="billing-projects-popover" id="moreProjectsMenu">
                                <div class="billing-projects-menu-row">
                                    <button type="button" data-submenu-toggle><span class="menu-copy"><i class="fa-solid fa-arrow-down-wide-short"></i> Sort by</span><i class="fa-solid fa-angle-right"></i></button>
                                    <div class="billing-projects-popover-submenu">
                                        <a class="<?php echo $sortColumn === 'created_time' ? 'is-active' : ''; ?>" href="<?php echo billing_escape($buildProjectsUrl(['sort' => 'created_time', 'order' => $sortColumn === 'created_time' && $sortOrder === 'desc' ? 'asc' : 'desc'])); ?>">Created Time <i class="fa-solid fa-arrow-<?php echo $sortColumn === 'created_time' && $sortOrder === 'asc' ? 'up' : 'down'; ?>"></i></a>
                                        <a class="<?php echo $sortColumn === 'last_modified_time' ? 'is-active' : ''; ?>" href="<?php echo billing_escape($buildProjectsUrl(['sort' => 'last_modified_time'])); ?>">Last Modified Time</a>
                                        <a class="<?php echo $sortColumn === 'customer_name' ? 'is-active' : ''; ?>" href="<?php echo billing_escape($buildProjectsUrl(['sort' => 'customer_name'])); ?>">Customer Name</a>
                                        <a class="<?php echo $sortColumn === 'project_name' ? 'is-active' : ''; ?>" href="<?php echo billing_escape($buildProjectsUrl(['sort' => 'project_name'])); ?>">Project Name</a>
                                        <a class="<?php echo $sortColumn === 'rate' ? 'is-active' : ''; ?>" href="<?php echo billing_escape($buildProjectsUrl(['sort' => 'rate'])); ?>">Rate</a>
                                    </div>
                                </div>
                                <div class="billing-projects-menu-row">
                                    <button type="button" data-submenu-toggle><span class="menu-copy"><i class="fa-solid fa-file-import"></i> Import</span><i class="fa-solid fa-angle-right"></i></button>
                                    <div class="billing-projects-popover-submenu">
                                        <a href="<?php echo billing_escape($buildProjectsUrl(['new' => '1'])); ?>">Import Projects</a>
                                        <a href="<?php echo billing_escape($buildProjectsUrl(['new' => '1'])); ?>">Import Project Tasks</a>
                                        <a href="timesheet.php">Import Timesheet</a>
                                    </div>
                                </div>
                                <div class="billing-projects-menu-row">
                                    <button type="button" data-submenu-toggle><span class="menu-copy"><i class="fa-solid fa-file-export"></i> Export</span><i class="fa-solid fa-angle-right"></i></button>
                                    <div class="billing-projects-popover-submenu">
                                        <a href="<?php echo billing_escape($buildProjectsUrl(['export' => 'projects'])); ?>">Export Projects</a>
                                        <a href="<?php echo billing_escape($buildProjectsUrl(['export' => 'tasks'])); ?>">Export Project Tasks</a>
                                        <a href="timesheet.php">Export Timesheet</a>
                                        <a href="<?php echo billing_escape($buildProjectsUrl(['export' => 'current'])); ?>">Export Current View</a>
                                    </div>
                                </div>
                                <div class="billing-projects-menu-row">
                                    <button type="button" data-submenu-toggle><span class="menu-copy"><i class="fa-solid fa-gear"></i> Preferences</span><i class="fa-solid fa-angle-right"></i></button>
                                    <div class="billing-projects-popover-submenu">
                                        <a href="<?php echo billing_escape($projectCustomFieldsPage); ?>">Project Preferences</a>
                                        <a href="timesheet.php">Timesheet Preferences</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if ($activeSettingsTab !== ''): ?>
                    <section class="billing-projects-settings-shell">
                        <div class="billing-projects-settings-head">
                            <h2>Projects</h2>
                            <?php if ($activeSettingsTab === 'fields'): ?>
                                <div style="display:flex;align-items:center;gap:16px;">
                                    <span style="color:#2563eb;font-size:14px;">Custom Fields Usage: <?php echo $customFieldsUsage; ?>/135</span>
                                    <a class="billing-projects-btn billing-projects-btn--green" href="<?php echo billing_escape($projectCustomFieldNewPage); ?>"><i class="fa-solid fa-plus"></i> New Custom Field</a>
                                </div>
                            <?php elseif ($activeSettingsTab === 'buttons'): ?>
                                <a class="billing-projects-btn billing-projects-btn--green" href="<?php echo billing_escape($projectCustomButtonsPage); ?>"><i class="fa-solid fa-plus"></i> New</a>
                            <?php else: ?>
                                <a class="billing-projects-btn billing-projects-btn--green" href="<?php echo billing_escape($projectRelatedListsPage); ?>"><i class="fa-solid fa-plus"></i> New Related List</a>
                            <?php endif; ?>
                        </div>
                        <div class="billing-projects-settings-tabs">
                            <a class="<?php echo $activeSettingsTab === 'fields' ? 'is-active' : ''; ?>" href="<?php echo billing_escape($projectCustomFieldsPage); ?>">Field Customization</a>
                            <a class="<?php echo $activeSettingsTab === 'buttons' ? 'is-active' : ''; ?>" href="<?php echo billing_escape($projectCustomButtonsPage); ?>">Custom Buttons</a>
                            <a class="<?php echo $activeSettingsTab === 'related' ? 'is-active' : ''; ?>" href="<?php echo billing_escape($projectRelatedListsPage); ?>">Related Lists</a>
                        </div>
                        <div class="billing-projects-settings-body">
                            <?php if ($activeSettingsTab === 'fields' && $showNewCustomField): ?>
                                <div class="billing-project-create-head">
                                    <h2>New Custom Field - Projects</h2>
                                    <a class="billing-project-close" href="<?php echo billing_escape($projectCustomFieldsPage); ?>" aria-label="Close"><i class="fa-solid fa-xmark"></i></a>
                                </div>
                                <?php if ($customFieldErrors !== []): ?>
                                    <div class="billing-project-errors">
                                        <?php foreach ($customFieldErrors as $error): ?>
                                            <div><?php echo billing_escape($error); ?></div>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                                <form method="post" class="billing-projects-custom-field-form">
                                    <input type="hidden" name="action" value="create_project_custom_field">
                                    <div class="billing-projects-custom-field-grid">
                                        <label class="field-label" for="label_name">Label Name*</label>
                                        <div class="billing-projects-field">
                                            <input id="label_name" type="text" name="label_name" value="<?php echo billing_escape($customFieldForm['label_name']); ?>">
                                        </div>

                                        <label class="field-label" for="data_type">Data Type*</label>
                                        <div class="billing-projects-field">
                                            <select id="data_type" name="data_type" data-custom-field-type>
                                                <option value="">Select data type</option>
                                                <?php foreach ($projectFieldTypeOptions as $value => $label): ?>
                                                    <option value="<?php echo billing_escape($value); ?>"<?php echo $customFieldForm['data_type'] === $value ? ' selected' : ''; ?>><?php echo billing_escape($label); ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>

                                        <label class="field-label" for="help_text">Help Text</label>
                                        <div class="billing-projects-field">
                                            <input id="help_text" type="text" name="help_text" value="<?php echo billing_escape($customFieldForm['help_text']); ?>">
                                        </div>

                                        <label class="field-label">Data Privacy</label>
                                        <div class="billing-projects-field">
                                            <label class="billing-projects-billable"><input type="checkbox" name="contains_pii" value="1"<?php echo $customFieldForm['contains_pii'] === '1' ? ' checked' : ''; ?>> PII</label>
                                            <label class="billing-projects-billable" style="margin-left:18px;"><input type="checkbox" name="contains_ephi" value="1"<?php echo $customFieldForm['contains_ephi'] === '1' ? ' checked' : ''; ?>> ePHI</label>
                                        </div>

                                        <label class="field-label">Prevent Duplicate Values</label>
                                        <div class="billing-projects-field">
                                            <label class="billing-projects-billable"><input type="radio" name="prevent_duplicates" value="1"<?php echo $customFieldForm['prevent_duplicates'] === '1' ? ' checked' : ''; ?>> Yes</label>
                                            <label class="billing-projects-billable" style="margin-left:18px;"><input type="radio" name="prevent_duplicates" value="0"<?php echo $customFieldForm['prevent_duplicates'] !== '1' ? ' checked' : ''; ?>> No</label>
                                        </div>

                                        <label class="field-label" for="input_format">Input Format</label>
                                        <div class="billing-projects-field">
                                            <input id="input_format" type="text" name="input_format" value="<?php echo billing_escape($customFieldForm['input_format']); ?>">
                                        </div>

                                        <label class="field-label" for="default_value">Default Value</label>
                                        <div class="billing-projects-field">
                                            <input id="default_value" type="text" name="default_value" value="<?php echo billing_escape($customFieldForm['default_value']); ?>">
                                        </div>

                                        <label class="field-label">Is Mandatory</label>
                                        <div class="billing-projects-field">
                                            <label class="billing-projects-billable"><input type="radio" name="is_mandatory" value="1"<?php echo $customFieldForm['is_mandatory'] === '1' ? ' checked' : ''; ?>> Yes</label>
                                            <label class="billing-projects-billable" style="margin-left:18px;"><input type="radio" name="is_mandatory" value="0"<?php echo $customFieldForm['is_mandatory'] !== '1' ? ' checked' : ''; ?>> No</label>
                                        </div>

                                        <div class="wide" style="padding-top:18px;border-top:1px solid #edf1f6;">
                                            <button class="billing-project-save" type="submit">Save</button>
                                            <a class="billing-project-cancel" href="<?php echo billing_escape($projectCustomFieldsPage); ?>">Cancel</a>
                                        </div>
                                    </div>
                                </form>
                            <?php elseif ($activeSettingsTab === 'fields'): ?>
                                <table class="billing-projects-settings-table">
                                    <thead>
                                        <tr>
                                            <th>FIELD NAME</th>
                                            <th>DATA TYPE</th>
                                            <th>MANDATORY</th>
                                            <th>STATUS</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr><td>Project Name</td><td>Text Box (Single Line)</td><td>Yes</td><td style="color:#16a34a;">Active</td></tr>
                                        <tr><td>Customer ID</td><td>Number</td><td>Yes</td><td style="color:#16a34a;">Active</td></tr>
                                        <tr><td>Project Status</td><td>Number</td><td>No</td><td style="color:#16a34a;">Active</td></tr>
                                        <?php foreach ($customFields as $field): ?>
                                            <tr>
                                                <td><a class="billing-projects-name" href="<?php echo billing_escape($projectCustomFieldNewPage); ?>"><?php echo billing_escape((string) ($field['label_name'] ?? 'Custom Field')); ?></a></td>
                                                <td><?php echo billing_escape((string) ($field['data_type'] ?? '')); ?></td>
                                                <td><?php echo !empty($field['is_mandatory']) ? 'Yes' : 'No'; ?></td>
                                                <td style="color:#16a34a;"><?php echo billing_escape((string) ($field['status'] ?? 'Active')); ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            <?php elseif ($activeSettingsTab === 'buttons'): ?>
                                <div class="billing-projects-settings-empty">
                                    <strong>Create buttons which perform actions set by you.</strong>
                                    What are you waiting for!
                                </div>
                            <?php else: ?>
                                <div class="billing-projects-settings-empty">
                                    <strong>Create custom related lists to access relevant information.</strong>
                                    Available from inside or outside the application.
                                </div>
                            <?php endif; ?>
                        </div>
                    </section>
                <?php elseif ($showNewProject): ?>
                    <section class="billing-project-create-card">
                        <div class="billing-project-create-head">
                            <h2>New Project</h2>
                            <a class="billing-project-close" href="<?php echo billing_escape($buildProjectsUrl(['new' => null])); ?>" aria-label="Close"><i class="fa-solid fa-xmark"></i></a>
                        </div>

                        <?php if ($projectErrors !== []): ?>
                            <div class="billing-project-errors">
                                <?php foreach ($projectErrors as $error): ?>
                                    <div><?php echo billing_escape($error); ?></div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>

                        <form method="post" class="billing-project-form">
                            <input type="hidden" name="action" value="create_project">

                            <section class="billing-project-form-section billing-project-form-section--soft">
                                <div class="billing-project-form-grid">
                                    <label>
                                        <span>Project Name*</span>
                                        <input type="text" name="project_name" value="<?php echo billing_escape($formData['project_name']); ?>">
                                    </label>

                                    <label>
                                        <span>Project Code</span>
                                        <input type="text" name="project_code" value="<?php echo billing_escape($formData['project_code']); ?>">
                                    </label>

                                    <label class="billing-project-form-wide">
                                        <span>Customer Name*</span>
                                        <div class="billing-project-select-shell">
                                            <select name="customer_name">
                                                <option value="">Select customer</option>
                                                <?php foreach ($customerOptions as $option): ?>
                                                    <option value="<?php echo billing_escape($option); ?>"<?php echo $formData['customer_name'] === $option ? ' selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                            <span class="billing-project-select-icon"><i class="fa-solid fa-magnifying-glass"></i></span>
                                        </div>
                                    </label>

                                    <label class="billing-project-form-wide">
                                        <span>Billing Method*</span>
                                        <select name="billing_method">
                                            <?php foreach ($billingMethods as $value => $label): ?>
                                                <option value="<?php echo billing_escape($value); ?>"<?php echo $formData['billing_method'] === $value ? ' selected' : ''; ?>><?php echo billing_escape($label); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </label>

                                    <label class="billing-project-form-wide">
                                        <span>Description</span>
                                        <textarea name="description_text" rows="4" placeholder="Max. 2000 characters"><?php echo billing_escape($formData['description_text']); ?></textarea>
                                    </label>
                                </div>
                            </section>

                            <section class="billing-project-form-section">
                                <h3>Budget</h3>
                                <div class="billing-project-budget-grid">
                                    <label>
                                        <span>Cost Budget</span>
                                        <div class="billing-project-currency-input">
                                            <strong>INR</strong>
                                            <input type="number" step="0.01" name="cost_budget" value="<?php echo billing_escape($formData['cost_budget']); ?>">
                                        </div>
                                    </label>
                                    <label>
                                        <span>Revenue Budget</span>
                                        <div class="billing-project-currency-input">
                                            <strong>INR</strong>
                                            <input type="number" step="0.01" name="revenue_budget" value="<?php echo billing_escape($formData['revenue_budget']); ?>">
                                        </div>
                                    </label>
                                </div>
                                <a class="billing-project-inline-link" href="projects.php?new=1">Add budget for project hours.</a>
                            </section>

                            <section class="billing-project-form-section">
                                <div class="billing-project-section-head">
                                    <h3>Users</h3>
                                </div>
                                <table class="billing-project-mini-table">
                                    <thead>
                                        <tr>
                                            <th>S.NO</th>
                                            <th>USER</th>
                                            <th>EMAIL</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($formData['users'] as $index => $row): ?>
                                            <tr>
                                                <td><?php echo $index + 1; ?></td>
                                                <td>
                                                    <input type="text" name="users[<?php echo $index; ?>][display_name]" value="<?php echo billing_escape((string) $row['display_name']); ?>">
                                                    <input type="hidden" name="users[<?php echo $index; ?>][role_label]" value="<?php echo billing_escape((string) ($row['role_label'] ?? 'Admin')); ?>">
                                                </td>
                                                <td><input type="email" name="users[<?php echo $index; ?>][email]" value="<?php echo billing_escape((string) $row['email']); ?>"></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                                <button class="billing-project-soft-add" type="button"><i class="fa-solid fa-circle-plus"></i> Add User</button>
                            </section>

                            <section class="billing-project-form-section">
                                <div class="billing-project-section-head">
                                    <h3>Project Tasks</h3>
                                    <a class="billing-project-inline-link" href="projects.php?new=1">Import project tasks from existing projects.</a>
                                </div>
                                <table class="billing-project-mini-table">
                                    <thead>
                                        <tr>
                                            <th>S.NO</th>
                                            <th>TASK NAME</th>
                                            <th>DESCRIPTION</th>
                                            <th>BILLABLE</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($formData['tasks'] as $index => $row): ?>
                                            <tr>
                                                <td><?php echo $index + 1; ?></td>
                                                <td><input type="text" name="tasks[<?php echo $index; ?>][task_name]" value="<?php echo billing_escape((string) $row['task_name']); ?>"></td>
                                                <td><input type="text" name="tasks[<?php echo $index; ?>][description_text]" value="<?php echo billing_escape((string) $row['description_text']); ?>"></td>
                                                <td class="is-center">
                                                    <input type="checkbox" name="tasks[<?php echo $index; ?>][is_billable]" value="1"<?php echo !empty($row['is_billable']) ? ' checked' : ''; ?>>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                                <button class="billing-project-soft-add" type="button"><i class="fa-solid fa-circle-plus"></i> Add Project Task</button>
                            </section>

                            <div class="billing-project-watchlist">
                                <label>
                                    <input type="checkbox" name="watchlist_enabled" value="1"<?php echo $formData['watchlist_enabled'] === '1' ? ' checked' : ''; ?>>
                                    <span>Add to the watchlist on my dashboard</span>
                                </label>
                            </div>

                            <div class="billing-project-form-actions">
                                <button class="billing-project-save" type="submit">Save</button>
                                <a class="billing-project-cancel" href="<?php echo billing_escape($buildProjectsUrl(['new' => null])); ?>">Cancel</a>
                            </div>
                        </form>
                    </section>
                <?php elseif ($view === 'cards'): ?>
                    <section class="billing-project-cards-wrap">
                        <div class="billing-project-cards-grid">
                            <?php foreach ($projects as $project): ?>
                                <article class="billing-project-card">
                                    <h3><?php echo billing_escape((string) ($project['project_name'] ?? 'Untitled')); ?></h3>
                                    <p><?php echo billing_escape((string) (($project['customer_name'] ?? '') !== '' ? $project['customer_name'] : '-')); ?></p>
                                    <div class="billing-project-card-hours-label">Logged Hours</div>
                                    <strong><?php echo billing_escape(billing_projects_hours_label((int) ($project['logged_seconds'] ?? 0))); ?></strong>
                                    <div class="billing-project-card-actions">
                                        <a href="<?php echo billing_escape($buildProjectsUrl(['timer' => '1', 'task_mode' => 'select'])); ?>">Log Time</a>
                                        <button type="button">Create Expense</button>
                                    </div>
                                </article>
                            <?php endforeach; ?>
                        </div>
                    </section>
                <?php else: ?>
                    <section class="billing-projects-table-card">
                        <table class="billing-projects-table">
                            <thead>
                                <tr>
                                    <th class="is-icon"><i class="fa-solid fa-sliders"></i></th>
                                    <th class="is-check"><input type="checkbox" aria-label="Select all projects"></th>
                                    <th>CUSTOMER NAME</th>
                                    <th>PROJECT NAME</th>
                                    <th>BILLING METHOD</th>
                                    <th class="is-amount">RATE</th>
                                    <th class="is-icon"><i class="fa-solid fa-magnifying-glass"></i></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($projects === []): ?>
                                    <tr>
                                        <td class="billing-projects-empty" colspan="7">No projects found.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($projects as $project): ?>
                                        <tr>
                                            <td></td>
                                            <td class="is-check"><input type="checkbox" aria-label="Select <?php echo billing_escape((string) ($project['project_name'] ?? '')); ?>"></td>
                                            <td><?php echo billing_escape((string) (($project['customer_name'] ?? '') !== '' ? $project['customer_name'] : '-')); ?></td>
                                            <td><a class="billing-projects-name" href="projects.php"><?php echo billing_escape((string) ($project['project_name'] ?? '')); ?></a></td>
                                            <td class="is-muted"><?php echo billing_escape(billing_project_billing_method_label((string) ($project['billing_method'] ?? 'project_hours'))); ?></td>
                                            <td class="is-amount"><?php echo billing_escape(str_replace('INR ', '₹', billing_projects_rate_label($project))); ?></td>
                                            <td></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </section>
                <?php endif; ?>

                <?php if ($showTimerModal): ?>
                    <div class="billing-projects-timer-overlay">
                        <div class="billing-projects-timer-modal">
                            <div class="billing-projects-timer-head">
                                <i class="fa-regular fa-clock"></i>
                                <span>START TIMER</span>
                                <strong id="billingProjectsModalTimer" data-running="0" data-elapsed="0">00h : 00m : 00s</strong>
                                <a class="billing-projects-timer-close" href="<?php echo billing_escape($buildProjectsUrl(['timer' => null, 'task_mode' => null])); ?>" aria-label="Close"><i class="fa-solid fa-xmark"></i></a>
                            </div>
                            <form method="post">
                                <input type="hidden" name="action" value="start_project_timer">
                                <input type="hidden" name="task_mode" id="projectTimerTaskModeInput" value="<?php echo billing_escape($timerTaskMode); ?>">
                                <div class="billing-projects-timer-form">
                                    <?php if ($timerErrors !== []): ?>
                                        <div class="billing-projects-timer-errors">
                                            <?php foreach ($timerErrors as $error): ?>
                                                <div><?php echo billing_escape($error); ?></div>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php endif; ?>

                                    <div class="billing-projects-field">
                                        <label>Project Name*</label>
                                        <select id="projectTimerProjectSelect" name="project_id">
                                            <option value="">Select a project</option>
                                            <?php foreach ($projectOptionsById as $projectOption): ?>
                                                <option value="<?php echo (int) $projectOption['id']; ?>"<?php echo (string) $projectOption['id'] === $timerForm['project_id'] ? ' selected' : ''; ?>><?php echo billing_escape((string) $projectOption['name']); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>

                                    <div class="billing-projects-field">
                                        <div class="billing-projects-inline-row">
                                            <label>Task Name*</label>
                                            <?php if ($timerTaskMode === 'create'): ?>
                                                <a class="billing-projects-task-mode-link" href="<?php echo billing_escape($buildProjectsUrl(['timer' => '1', 'task_mode' => 'select'])); ?>">Select from list</a>
                                            <?php endif; ?>
                                        </div>

                                        <?php if ($timerTaskMode === 'create'): ?>
                                            <input id="projectTimerTaskCreateInput" type="text" name="task_name" value="<?php echo billing_escape($timerForm['task_name']); ?>" placeholder="Enter task name">
                                        <?php else: ?>
                                            <select id="projectTimerTaskSelect" name="task_name" data-selected-task="<?php echo billing_escape($timerForm['task_name']); ?>">
                                                <option value="">Select task</option>
                                            </select>
                                            <div style="margin-top:10px;">
                                                <a class="billing-projects-task-mode-link" href="<?php echo billing_escape($buildProjectsUrl(['timer' => '1', 'task_mode' => 'create'])); ?>"><i class="fa-solid fa-circle-plus"></i> New Task</a>
                                            </div>
                                        <?php endif; ?>
                                    </div>

                                    <div class="billing-projects-field">
                                        <label class="billing-projects-billable"><input type="checkbox" name="billable" value="1"<?php echo $timerForm['billable'] === '1' ? ' checked' : ''; ?>> Billable</label>
                                    </div>

                                    <div class="billing-projects-field">
                                        <label for="projectTimerNotes">Notes</label>
                                        <textarea id="projectTimerNotes" name="notes" placeholder="Add notes"><?php echo billing_escape($timerForm['notes']); ?></textarea>
                                    </div>
                                </div>
                                <div class="billing-projects-timer-actions">
                                    <button class="billing-project-save" type="submit">Start Timer</button>
                                    <a class="billing-project-cancel" href="<?php echo billing_escape($buildProjectsUrl(['timer' => null, 'task_mode' => null])); ?>">Cancel</a>
                                </div>
                            </form>
                        </div>
                    </div>
                <?php endif; ?>
            </section>
        </main>
    </div>
</div>
<?php if (($timerState['status'] ?? '') !== ''): ?>
    <div class="billing-projects-timer-dock">
        <i class="fa-regular fa-clock"></i>
        <strong id="billingProjectsDockTimer" data-running="<?php echo ($timerState['status'] ?? '') === 'running' ? '1' : '0'; ?>" data-elapsed="<?php echo $activeTimerSeconds; ?>" data-started="<?php echo (int) ($timerState['started_at'] ?? time()); ?>"><?php echo billing_escape(billing_projects_timer_label($activeTimerSeconds)); ?></strong>
        <div class="billing-projects-dock-actions">
            <?php if (($timerState['status'] ?? '') === 'running'): ?>
                <form method="post">
                    <input type="hidden" name="action" value="pause_project_timer">
                    <button type="submit" aria-label="Pause"><i class="fa-solid fa-pause"></i></button>
                </form>
            <?php else: ?>
                <form method="post">
                    <input type="hidden" name="action" value="resume_project_timer">
                    <button type="submit" aria-label="Resume"><i class="fa-solid fa-play"></i></button>
                </form>
            <?php endif; ?>
            <form method="post">
                <input type="hidden" name="action" value="stop_project_timer">
                <button type="submit" aria-label="Stop"><i class="fa-regular fa-circle-stop"></i></button>
            </form>
        </div>
    </div>
<?php endif; ?>
<script src="assets/billing.js"></script>
<script>
window.billingProjectOptions = <?php echo json_encode(array_values($projectOptionsById), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;

(function () {
    function formatTimer(seconds) {
        seconds = Math.max(0, seconds);
        var hours = Math.floor(seconds / 3600);
        var minutes = Math.floor((seconds % 3600) / 60);
        var remaining = seconds % 60;
        return String(hours).padStart(2, '0') + 'h : ' + String(minutes).padStart(2, '0') + 'm : ' + String(remaining).padStart(2, '0') + 's';
    }

    document.querySelectorAll('[data-popover-toggle]').forEach(function (trigger) {
        trigger.addEventListener('click', function (event) {
            event.stopPropagation();
            var targetId = trigger.getAttribute('data-popover-toggle');
            var target = document.getElementById(targetId);
            if (!target) {
                return;
            }

            document.querySelectorAll('.billing-projects-popover.is-open').forEach(function (popover) {
                if (popover !== target) {
                    popover.classList.remove('is-open');
                }
            });

            target.classList.toggle('is-open');
        });
    });

    document.addEventListener('click', function (event) {
        document.querySelectorAll('.billing-projects-popover.is-open').forEach(function (popover) {
            if (!popover.parentElement || !popover.parentElement.contains(event.target)) {
                popover.classList.remove('is-open');
            }
        });
    });

    document.querySelectorAll('[data-submenu-toggle]').forEach(function (trigger) {
        trigger.addEventListener('click', function (event) {
            event.preventDefault();
            var row = trigger.closest('.billing-projects-menu-row');
            if (!row) {
                return;
            }
            row.parentElement.querySelectorAll('.billing-projects-menu-row').forEach(function (other) {
                if (other !== row) {
                    other.classList.remove('is-open');
                }
            });
            row.classList.toggle('is-open');
        });
    });

    document.querySelectorAll('#billingProjectsToolbarTimer, #billingProjectsDockTimer, #billingProjectsModalTimer').forEach(function (node) {
        var running = node.getAttribute('data-running') === '1';
        var elapsed = parseInt(node.getAttribute('data-elapsed') || '0', 10);
        var started = parseInt(node.getAttribute('data-started') || '0', 10);
        node.textContent = formatTimer(elapsed);
        if (!running) {
            return;
        }
        window.setInterval(function () {
            var nowSeconds = Math.floor(Date.now() / 1000);
            node.textContent = formatTimer(elapsed + Math.max(nowSeconds - started, 0));
        }, 1000);
    });

    var projectSelect = document.getElementById('projectTimerProjectSelect');
    var taskSelect = document.getElementById('projectTimerTaskSelect');
    var taskCreateInput = document.getElementById('projectTimerTaskCreateInput');

    function getSelectedProject() {
        var projectId = parseInt(projectSelect ? projectSelect.value : '0', 10);
        var options = Array.isArray(window.billingProjectOptions) ? window.billingProjectOptions : [];
        for (var i = 0; i < options.length; i += 1) {
            if (parseInt(options[i].id, 10) === projectId) {
                return options[i];
            }
        }
        return null;
    }

    function syncTaskCreateInput() {
        return;
    }

    function renderTaskList() {
        if (!taskSelect) {
            return;
        }
        var project = getSelectedProject();
        var items = project && Array.isArray(project.tasks) ? project.tasks : [];
        var selectedTask = taskSelect.getAttribute('data-selected-task') || taskSelect.value || '';
        taskSelect.innerHTML = '';

        var placeholder = document.createElement('option');
        placeholder.value = '';
        placeholder.textContent = items.length === 0 ? 'No tasks available' : 'Select task';
        taskSelect.appendChild(placeholder);

        items.forEach(function (item) {
            var option = document.createElement('option');
            option.value = item.name;
            option.textContent = item.name;
            if (selectedTask === item.name) {
                option.selected = true;
            }
            taskSelect.appendChild(option);
        });
        taskSelect.setAttribute('data-selected-task', taskSelect.value);
    }

    if (projectSelect) {
        projectSelect.addEventListener('change', function () {
            if (taskSelect) {
                taskSelect.setAttribute('data-selected-task', '');
            }
            renderTaskList();
        });
    }

    renderTaskList();
    syncTaskCreateInput();
})();
</script>
</body>
</html>
