<?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'];
$entries = billing_get_project_time_entries($userId, $organizationId);
$projects = billing_get_projects($userId, $organizationId);
$customers = billing_get_customers($userId);

$display = isset($_GET['display']) && $_GET['display'] === 'calendar' ? 'calendar' : 'list';
$showSummary = isset($_GET['summary']) && $_GET['summary'] === '1';
$showPeriodMenu = isset($_GET['period_menu']) && $_GET['period_menu'] === '1';
$showMoreMenu = isset($_GET['menu']) && $_GET['menu'] === '1';

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

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

if (!function_exists('billing_timesheet_month_start')) {
    function billing_timesheet_month_start(string $ym = ''): DateTimeImmutable
    {
        if ($ym !== '' && preg_match('/^\d{4}-\d{2}$/', $ym) === 1) {
            $date = DateTimeImmutable::createFromFormat('Y-m-d', $ym . '-01');
            if ($date instanceof DateTimeImmutable) {
                return $date;
            }
        }
        return new DateTimeImmutable('first day of this month');
    }
}

$monthStart = billing_timesheet_month_start((string) ($_GET['month'] ?? ''));
$calendarStart = $monthStart->modify('last sunday');
$calendarEnd = $monthStart->modify('last day of this month')->modify('next saturday');

$entriesByDate = [];
$totalLoggedSeconds = 0;
$totalBillableSeconds = 0;
$totalUnbillableSeconds = 0;
$totalUnbilledSeconds = 0;

foreach ($entries as $entry) {
    $entryDate = (string) ($entry['entry_date'] ?? '');
    $seconds = (int) ($entry['duration_seconds'] ?? 0);
    if ($entryDate !== '') {
        if (!isset($entriesByDate[$entryDate])) {
            $entriesByDate[$entryDate] = [];
        }
        $entriesByDate[$entryDate][] = $entry;
    }
    $totalLoggedSeconds += $seconds;
    if (strcasecmp((string) ($entry['billing_status'] ?? ''), 'Unbilled') === 0) {
        $totalUnbilledSeconds += $seconds;
    } else {
        $totalBillableSeconds += $seconds;
    }
}
$totalNonBillableSeconds = max(0, $totalLoggedSeconds - $totalBillableSeconds);

$periodOptions = ['All', 'Today', 'This Week', 'This Month', 'Last Month'];
$selectedPeriod = 'All';

$projectChoices = [];
foreach ($projects as $project) {
    $projectName = trim((string) ($project['project_name'] ?? ''));
    if ($projectName !== '') {
        $projectChoices[] = $projectName;
    }
}
$projectChoices = array_values(array_unique($projectChoices));
sort($projectChoices, SORT_NATURAL | SORT_FLAG_CASE);

$customerChoices = [];
foreach ($customers as $customer) {
    $customerName = trim((string) ($customer['customer_name'] ?? ''));
    if ($customerName !== '') {
        $customerChoices[] = $customerName;
    }
}
$customerChoices = array_values(array_unique($customerChoices));
sort($customerChoices, SORT_NATURAL | SORT_FLAG_CASE);

$listUrl = 'timesheet.php';
$calendarUrl = 'timesheet.php?display=calendar';
?>
<!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>Timesheet</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-timesheet-views-restore">
</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-timesheet-page">
            <section class="billing-timesheet-shell">
                <div class="billing-timesheet-head">
                    <div class="billing-timesheet-tabs">
                        <a class="is-active" href="<?php echo billing_escape($display === 'calendar' ? $calendarUrl : $listUrl); ?>">All Timesheets <i class="fa-solid fa-angle-down"></i></a>
                    </div>
                    <div class="billing-timesheet-actions">
                        <a class="billing-timesheet-summary" href="<?php echo billing_escape($display === 'calendar' ? $calendarUrl . '&summary=1' : 'timesheet.php?summary=1'); ?>"><i class="fa-solid fa-chart-column"></i> Summary</a>
                        <div class="billing-timesheet-view-toggle" aria-label="Timesheet view toggle">
                            <a class="<?php echo $display === 'list' ? 'is-active' : ''; ?>" href="timesheet.php"><i class="fa-solid fa-list"></i></a>
                            <a class="<?php echo $display === 'calendar' ? 'is-active' : ''; ?>" href="timesheet.php?display=calendar"><i class="fa-regular fa-calendar"></i></a>
                        </div>
                        <button class="billing-timesheet-btn billing-timesheet-btn--green" type="button"><i class="fa-regular fa-clock"></i> Start</button>
                        <button class="billing-timesheet-btn billing-timesheet-btn--green-strong" type="button"><i class="fa-solid fa-plus"></i> New Log Entry <i class="fa-solid fa-angle-down"></i></button>
                        <a class="billing-timesheet-icon-btn" href="<?php echo billing_escape($display === 'calendar' ? $calendarUrl . '&menu=1' : 'timesheet.php?menu=1'); ?>" aria-label="More actions">
                            <i class="fa-solid fa-ellipsis"></i>
                        </a>
                    </div>
                </div>

                <?php if ($display === 'list'): ?>
                    <div class="billing-timesheet-filters">
                        <span class="billing-timesheet-filter-title">VIEW BY:</span>
                        <a class="billing-timesheet-filter-link" href="timesheet.php?period_menu=1">Period: <strong><?php echo billing_escape($selectedPeriod); ?></strong> <i class="fa-solid fa-angle-down"></i></a>
                        <button type="button"><i class="fa-regular fa-user"></i> Select customer <i class="fa-solid fa-angle-down"></i></button>
                        <button type="button"><i class="fa-regular fa-folder-open"></i> Select a project <i class="fa-solid fa-angle-down"></i></button>
                        <button type="button"><i class="fa-solid fa-users"></i> Select user <i class="fa-solid fa-angle-down"></i></button>
                    </div>
                <?php endif; ?>

                <?php if ($showSummary): ?>
                    <div class="billing-timesheet-summary-popover">
                        <div>
                            <span>Logged Hours</span>
                            <strong class="is-green"><?php echo billing_escape(billing_timesheet_hours_label($totalLoggedSeconds)); ?></strong>
                        </div>
                        <div>
                            <span>Non-Billable Hours</span>
                            <strong class="is-muted"><?php echo billing_escape(billing_timesheet_hours_label($totalNonBillableSeconds)); ?></strong>
                        </div>
                        <div>
                            <span>Billed Hours</span>
                            <strong class="is-green"><?php echo billing_escape(billing_timesheet_hours_label($totalBillableSeconds)); ?></strong>
                        </div>
                        <div>
                            <span>Unbilled Hours</span>
                            <strong class="is-orange"><?php echo billing_escape(billing_timesheet_hours_label($totalUnbilledSeconds)); ?></strong>
                        </div>
                        <p>This report is based on the applied filters.</p>
                    </div>
                <?php endif; ?>

                <?php if ($showPeriodMenu && $display === 'list'): ?>
                    <div class="billing-timesheet-period-menu">
                        <div class="billing-timesheet-period-search">
                            <i class="fa-solid fa-magnifying-glass"></i>
                            <input type="search" placeholder="Search">
                        </div>
                        <div class="billing-timesheet-period-group">All</div>
                        <?php foreach ($periodOptions as $index => $option): ?>
                            <div class="billing-timesheet-period-item<?php echo $index === 0 ? ' is-active' : ''; ?>">
                                <span><?php echo billing_escape($option); ?></span>
                                <?php if ($index === 0): ?><i class="fa-solid fa-check"></i><?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>

                <?php if ($showMoreMenu): ?>
                    <div class="billing-timesheet-more-menu">
                        <a href="<?php echo billing_escape($display === 'calendar' ? $calendarUrl . '&menu=1' : 'timesheet.php?menu=1'); ?>">Sort by <i class="fa-solid fa-angle-right"></i></a>
                        <a href="<?php echo billing_escape($display === 'calendar' ? $calendarUrl . '&menu=1' : 'timesheet.php?menu=1'); ?>"><i class="fa-solid fa-file-import"></i> Import <i class="fa-solid fa-angle-right"></i></a>
                        <a href="<?php echo billing_escape($display === 'calendar' ? $calendarUrl . '&menu=1' : 'timesheet.php?menu=1'); ?>"><i class="fa-solid fa-file-export"></i> Export <i class="fa-solid fa-angle-right"></i></a>
                        <a href="<?php echo billing_escape($display === 'calendar' ? $calendarUrl . '&menu=1' : 'timesheet.php?menu=1'); ?>"><i class="fa-solid fa-gear"></i> Preferences <i class="fa-solid fa-angle-right"></i></a>
                    </div>
                <?php endif; ?>

                <?php if ($display === 'calendar'): ?>
                    <section class="billing-timesheet-calendar-card">
                        <div class="billing-timesheet-calendar-head">
                            <h2>Timesheets</h2>
                            <div class="billing-timesheet-calendar-nav">
                                <a href="timesheet.php?display=calendar&amp;month=<?php echo billing_escape($monthStart->modify('-1 month')->format('Y-m')); ?>"><i class="fa-solid fa-angle-left"></i></a>
                                <strong><?php echo billing_escape($monthStart->format('F Y')); ?></strong>
                                <a href="timesheet.php?display=calendar&amp;month=<?php echo billing_escape($monthStart->modify('+1 month')->format('Y-m')); ?>"><i class="fa-solid fa-angle-right"></i></a>
                            </div>
                        </div>
                        <table class="billing-timesheet-calendar">
                            <thead>
                                <tr>
                                    <th>SUNDAY</th>
                                    <th>MONDAY</th>
                                    <th>TUESDAY</th>
                                    <th>WEDNESDAY</th>
                                    <th>THURSDAY</th>
                                    <th>FRIDAY</th>
                                    <th>SATURDAY</th>
                                    <th>TOTAL</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $cursor = $calendarStart;
                                while ($cursor <= $calendarEnd):
                                    $weekSeconds = 0;
                                ?>
                                    <tr>
                                        <?php for ($day = 0; $day < 7; $day++): ?>
                                            <?php
                                            $dateKey = $cursor->format('Y-m-d');
                                            $dayEntries = $entriesByDate[$dateKey] ?? [];
                                            $daySeconds = 0;
                                            foreach ($dayEntries as $dayEntry) {
                                                $daySeconds += (int) ($dayEntry['duration_seconds'] ?? 0);
                                            }
                                            $weekSeconds += $daySeconds;
                                            ?>
                                            <td class="<?php echo $cursor->format('Y-m') !== $monthStart->format('Y-m') ? 'is-outside-month' : ''; ?>">
                                                <div class="billing-timesheet-calendar-date-row">
                                                    <span class="billing-timesheet-calendar-date<?php echo $cursor->format('Y-m-d') === (new DateTimeImmutable('today'))->format('Y-m-d') ? ' is-today' : ''; ?>"><?php echo billing_escape($cursor->format('j')); ?></span>
                                                    <button type="button"><i class="fa-solid fa-plus"></i></button>
                                                </div>
                                                <?php if ($daySeconds > 0): ?>
                                                    <div class="billing-timesheet-calendar-entry">
                                                        <strong><?php echo billing_escape(billing_timesheet_hours_label($daySeconds)); ?></strong>
                                                        <span>Total Logged Hours</span>
                                                    </div>
                                                    <a class="billing-timesheet-calendar-count" href="timesheet.php"><?php echo count($dayEntries); ?> Timesheets <i class="fa-solid fa-angle-right"></i></a>
                                                <?php else: ?>
                                                    <div class="billing-timesheet-calendar-empty">No logged hours</div>
                                                <?php endif; ?>
                                            </td>
                                            <?php $cursor = $cursor->modify('+1 day'); ?>
                                        <?php endfor; ?>
                                        <td class="billing-timesheet-calendar-total"><?php echo billing_escape(billing_timesheet_hours_label($weekSeconds)); ?></td>
                                    </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                        <div class="billing-timesheet-calendar-footer">
                            <span>Total Hours :</span>
                            <strong><?php echo billing_escape(billing_timesheet_hours_label($totalLoggedSeconds)); ?></strong>
                        </div>
                    </section>
                <?php else: ?>
                    <section class="billing-timesheet-table-card">
                        <table class="billing-timesheet-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 timesheet entries"></th>
                                    <th>DATE</th>
                                    <th>PROJECT</th>
                                    <th>CUSTOMER</th>
                                    <th>TASK</th>
                                    <th>USER</th>
                                    <th class="is-amount">TIME</th>
                                    <th>BILLING STATUS</th>
                                    <th class="is-actions"><i class="fa-solid fa-magnifying-glass"></i></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($entries === []): ?>
                                    <tr>
                                        <td class="billing-timesheet-empty" colspan="10">No time entries found.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($entries as $entry): ?>
                                        <?php
                                        $entryDate = (string) ($entry['entry_date'] ?? '');
                                        $entryDateLabel = $entryDate !== '' ? date('d/m/Y', strtotime($entryDate)) : '-';
                                        $hours = (int) ($entry['duration_seconds'] ?? 0);
                                        ?>
                                        <tr>
                                            <td></td>
                                            <td class="is-check"><input type="checkbox" aria-label="Select entry <?php echo (int) ($entry['id'] ?? 0); ?>"></td>
                                            <td><?php echo billing_escape($entryDateLabel); ?></td>
                                            <td><a class="billing-timesheet-name" href="timesheet.php"><?php echo billing_escape((string) (($entry['project_name'] ?? '') !== '' ? $entry['project_name'] : '-')); ?></a></td>
                                            <td><?php echo billing_escape((string) (($entry['customer_name'] ?? '') !== '' ? $entry['customer_name'] : '-')); ?></td>
                                            <td class="is-muted"><?php echo billing_escape((string) (($entry['task_name'] ?? '') !== '' ? $entry['task_name'] : '-')); ?></td>
                                            <td class="is-muted"><?php echo billing_escape((string) (($entry['user_display_name'] ?? '') !== '' ? $entry['user_display_name'] : '-')); ?></td>
                                            <td class="is-amount"><?php echo billing_escape(billing_timesheet_hours_label($hours)); ?></td>
                                            <td class="billing-timesheet-status"><?php echo billing_escape((string) (($entry['billing_status'] ?? '') !== '' ? $entry['billing_status'] : 'Unbilled')); ?></td>
                                            <td class="billing-timesheet-row-actions">
                                                <button type="button" aria-label="Timer"><i class="fa-regular fa-clock"></i></button>
                                                <button type="button" aria-label="Edit"><i class="fa-regular fa-pen-to-square"></i></button>
                                                <button type="button" aria-label="Settings"><i class="fa-solid fa-gear"></i></button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </section>
                <?php endif; ?>
            </section>
        </main>
    </div>
</div>
<script src="assets/billing.js"></script>
</body>
</html>
