<?php
require_once __DIR__ . '/includes/settings_helpers.php';
require_once __DIR__ . '/includes/tax_forms_module.php';

settings_require_auth();
settings_ensure_tables($conn);

$org = settings_get_current_org($conn);
$orgId = (int) ($org['id'] ?? 0);
$orgName = $_SESSION['org_name'] ?? 'demo';
$displayName = $_SESSION['username'] ?? $orgName;

$taxDetails = tax_details_get($conn, (string) ($org['id'] ?? ($_SESSION['org_id'] ?? '')));
$paySchedule = settings_get_pay_schedule($conn, $orgId);
$epfSettings = settings_get_statutory_component($conn, $orgId, 'epf');
$esiSettings = settings_get_statutory_component($conn, $orgId, 'esi');
$lwfSettings = settings_get_statutory_component($conn, $orgId, 'lwf');
$salaryTemplate = settings_get_salary_template($conn, $orgId);

$employeeCount = 0;
$employeeCountStmt = $conn->prepare("SELECT COUNT(*) AS total FROM employees WHERE organization_id = ? AND COALESCE(is_deleted, 0) = 0");
if ($employeeCountStmt) {
    $employeeCountStmt->bind_param('i', $orgId);
    $employeeCountStmt->execute();
    $employeeCountResult = $employeeCountStmt->get_result();
    if ($employeeCountResult && ($employeeCountRow = $employeeCountResult->fetch_assoc())) {
        $employeeCount = (int) ($employeeCountRow['total'] ?? 0);
    }
    $employeeCountStmt->close();
}

$payrunCount = 0;
$payrunCountStmt = $conn->prepare("SELECT COUNT(*) AS total FROM payruns WHERE org_id = ?");
if ($payrunCountStmt) {
    $payrunCountStmt->bind_param('s', $orgName);
    $payrunCountStmt->execute();
    $payrunCountResult = $payrunCountStmt->get_result();
    if ($payrunCountResult && ($payrunCountRow = $payrunCountResult->fetch_assoc())) {
        $payrunCount = (int) ($payrunCountRow['total'] ?? 0);
    }
    $payrunCountStmt->close();
}

$profileComplete = trim((string) ($org['organisation_name'] ?? '')) !== '' && trim((string) ($org['address_line1'] ?? '')) !== '' && trim((string) ($org['state'] ?? '')) !== '';
$taxComplete = trim((string) ($taxDetails['pan'] ?? '')) !== '' && trim((string) ($taxDetails['deductor_name'] ?? '')) !== '';
$payScheduleComplete = !empty($paySchedule['pay_frequency']) && !empty($paySchedule['first_pay_date']);
$statutorySubitems = [
    ['label' => "Employees' Provident Fund", 'href' => 'statutory_components.php?component=epf&mode=view', 'complete' => !empty($epfSettings['enabled'])],
    ['label' => "Employees' State Insurance", 'href' => 'statutory_components.php?component=esi&mode=view', 'complete' => !empty($esiSettings['enabled'])],
    ['label' => 'Labour Welfare Fund', 'href' => 'statutory_components.php?component=lwf&mode=view', 'complete' => !empty($lwfSettings['enabled'])],
    ['label' => 'Professional Tax', 'href' => 'statutory_components.php?component=pt&mode=view', 'complete' => $taxComplete],
];
$statutoryComplete = count(array_filter($statutorySubitems, static function (array $item): bool {
    return !empty($item['complete']);
})) === count($statutorySubitems);
$salaryManualComplete = settings_get_setup_step_state($conn, $orgId, 'salary_components');
$statutoryManualComplete = settings_get_setup_step_state($conn, $orgId, 'statutory_components');
$statutoryComplete = $statutoryComplete || $statutoryManualComplete;
$salaryComplete = (float) ($salaryTemplate['annual_ctc'] ?? 0) > 0 || $salaryManualComplete;
$employeesComplete = $employeeCount > 0;
$priorPayrollComplete = $payrunCount > 0;

$setupSteps = [
    ['label' => '1. Add Organisation Details', 'href' => 'orgprofile.php', 'completed' => $profileComplete],
    ['label' => '2. Provide your Tax Details', 'href' => 'tax_details.php', 'completed' => $taxComplete],
    ['label' => '3. Configure your Pay Schedule', 'href' => 'pay_schedule.php', 'completed' => $payScheduleComplete],
    [
        'label' => '4. Set up Statutory Components',
        'href' => 'statutory_components.php',
        'completed' => $statutoryComplete,
        'subitems' => $statutorySubitems,
    ],
    [
        'label' => '5. Set up Salary Components',
        'href' => 'salary_components.php',
        'completed' => $salaryComplete,
    ],
    ['label' => '6. Add Employees', 'href' => 'employees.php', 'completed' => $employeesComplete],
    ['label' => '7. Configure Prior Payroll', 'href' => 'payruns.php', 'completed' => $priorPayrollComplete],
];

$completedSetupSteps = count(array_filter($setupSteps, static function (array $step): bool {
    return !empty($step['completed']);
}));
$setupStepCount = count($setupSteps);
$setupProgress = $setupStepCount > 0 ? (int) round(($completedSetupSteps / $setupStepCount) * 100) : 0;
$allSetupComplete = $setupStepCount > 0 && $completedSetupSteps === $setupStepCount;

if (!$allSetupComplete) {
    header('Location: dashboard.php');
    exit();
}

date_default_timezone_set('Asia/Kolkata');
$nowTime = date('h:i A');
?>
<!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>Getting Started | Payroll</title>
<link rel="stylesheet" href="dashboard.css">
<link rel="stylesheet" href="assets/font-inter.css">
<link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
<style>
body.getting-started-page .dash-content{padding-bottom:64px;}
.getting-started-page .hero-card{background:transparent;border:0;box-shadow:none;padding-bottom:12px;}
.getting-started-page .hero-card h1{font-size:24px;margin-bottom:8px;}
.getting-started-page .hero-card .hero-sub{font-size:16px;color:#6b7280;margin-top:0;}
.getting-started-page .hero-card .hero-contact{display:block;margin-top:18px;color:#6b7280;font-size:14px;}
.getting-started-page .progress-card{margin-top:18px;}
.getting-started-page .setup-complete-note{background:#eff6ff;color:#1d4ed8;border:1px solid #bfdbfe;border-radius:12px;padding:12px 16px;margin:16px 0 4px;font-weight:600;}
</style>
</head>
<body class="dash-page getting-started-page" data-setup-complete="1">
<div class="dash-layout">
  <aside class="dash-sidebar">
    <div class="sidebar-brand">
      <img src="images/zoho-payroll-logo.svg" class="logo" alt="Zoho Payroll">
    </div>
    <div class="sidebar-scroll">
      <div class="sidebar-section">
        <div class="getting-started">
          <div class="gs-top">
            <i class="fa-solid fa-rocket-launch"></i>
            <span>Getting Started</span>
          </div>
          <div class="progress-bar">
            <div class="progress-fill" style="width:100%;"></div>
          </div>
        </div>
      </div>
      <nav class="sidebar-nav">
        <a class="nav-item active" href="dashboard.php"><i class="fa-solid fa-gauge-high"></i><span>Dashboard</span></a>
        <a class="nav-item" href="employees.php"><i class="fa-solid fa-users"></i><span>Employees</span></a>
        <a class="nav-item" href="payruns.php"><i class="fa-solid fa-money-bill-wave"></i><span>Pay Runs</span></a>
        <div class="nav-group">
          <button class="nav-item btn" type="button" data-nav-toggle><i class="fa-regular fa-square-check"></i><span>Approvals</span></button>
          <div class="nav-sub">
            <a class="nav-sub-item" href="reimbursements.php">Reimbursements</a>
            <a class="nav-sub-item" href="proof_of_investments.php">Proof Of Investments</a>
            <a class="nav-sub-item" href="salary_revision.php">Salary Revision</a>
          </div>
        </div>
        <a class="nav-item" href="form16.php"><i class="fa-regular fa-file-lines"></i><span>Form 16</span></a>
        <a class="nav-item" href="loans.php"><i class="fa-solid fa-hand-holding-dollar"></i><span>Loans</span></a>
        <a class="nav-item" href="giving.php"><i class="fa-solid fa-gift"></i><span>Giving</span></a>
        <a class="nav-item" href="documents.php"><i class="fa-regular fa-folder-open"></i><span>Documents</span></a>
        <a class="nav-item" href="reports.php"><i class="fa-solid fa-chart-pie"></i><span>Reports</span></a>
        <a class="nav-item" href="settings.php"><i class="fa-solid fa-gear"></i><span>Settings</span></a>
      </nav>
    </div>
    <div class="sidebar-footer">
      <a class="support-link" href="support.php">Contact Support</a>
    </div>
    <div class="support-tile">
      <div class="support-title">Track TDS Liabilities and Generate Form 24Q</div>
      <a class="support-action" href="support.php?promo=tds">View Details</a>
    </div>
  </aside>

  <main class="dash-main">
    <header class="dash-topbar">
      <div class="search-box">
        <i class="fa-solid fa-magnifying-glass search-icon"></i>
        <input type="text" placeholder="Search in Employee">
      </div>
      <div class="topbar-actions">
        <span class="trial">Your trial expires in 7 day(s). <a href="dashboard.php?modal=upgrade" class="upgrade-link">Upgrade</a></span>
        <a class="pill ghost org-toggle" href="dashboard.php?drawer=org" data-tooltip="Organisation menu"><span class="pill-label"><?php echo htmlspecialchars($orgName ?: 'demo'); ?></span><i class="fa-solid fa-angle-down"></i></a>
        <a class="top-icon icon-btn" href="dashboard.php?drawer=notif" data-tooltip="Notifications"><i class="fa-regular fa-bell"></i></a>
        <a class="top-icon top-link" href="settings.php" data-tooltip="Settings"><i class="fa-solid fa-gear"></i></a>
        <a class="top-icon icon-btn app-menu" href="dashboard.php?drawer=apps" data-tooltip="Apps"><i class="fa-solid fa-table-cells-large"></i></a>
        <a class="top-icon icon-btn top-avatar" href="dashboard.php?drawer=profile" data-tooltip="Profile"><i class="fa-regular fa-circle-user"></i></a>
        <span class="avatar" data-tooltip="Profile"><?php echo strtoupper(substr($orgName, 0, 1)); ?></span>
      </div>
    </header>

    <section class="dash-content">
      <div class="hero-card">
        <h1>Welcome <?php echo htmlspecialchars($displayName); ?>!</h1>
        <p class="hero-sub">Set up your organisation before you run your first payroll.</p>
        <div class="hero-contact">Need help? Call us Mon-Fri, 9 AM-7 PM at 18005726671 (toll-free).</div>
      </div>

      <div class="webinar-bar">
        <span class="webinar-icon"><i class="fa-solid fa-display"></i></span> Live webinar: An overview of Zoho Payroll
        <span class="calendar">Tuesday or Thursday @3:30PM IST</span>
        <a class="secondary-btn small" href="support.php?promo=webinar">Register Now</a>
      </div>

      <div class="progress-card">
        <header class="progress-head">
          <div>
            <div class="label">Get started with Zoho Payroll</div>
            <div class="sub">Complete the following steps to have a hassle-free payroll experience</div>
          </div>
          <div class="progress-indicator">
            <span class="bar"><span class="fill" style="width:100%;"></span></span>
            <span class="count">7/7 Completed</span>
          </div>
        </header>

        <div class="setup-complete-note">All 7 setup steps are completed. Your organisation is ready.</div>

        <div class="steps">
          <?php foreach ($setupSteps as $setupStep): ?>
            <div class="step done">
              <span class="check"><i class="fa-solid fa-check"></i></span>
              <a class="step-text" href="<?php echo htmlspecialchars($setupStep['href']); ?>"><?php echo htmlspecialchars($setupStep['label']); ?></a>
              <span class="arrow">&rsaquo;</span>
              <a class="status status-link" href="<?php echo htmlspecialchars($setupStep['href']); ?>">COMPLETED</a>
            </div>
            <?php if (!empty($setupStep['subitems'])): ?>
              <div class="step-sublist">
                <?php foreach ($setupStep['subitems'] as $subitem): ?>
                  <div class="step-subitem">
                    <span class="subcheck complete"><i class="fa-solid fa-check"></i></span>
                    <?php if (!empty($subitem['href'])): ?>
                      <a class="subtext sub-link" href="<?php echo htmlspecialchars((string) $subitem['href']); ?>">
                        <?php echo htmlspecialchars((string) $subitem['label']); ?>
                      </a>
                    <?php else: ?>
                      <span class="subtext sub-link"><?php echo htmlspecialchars((string) $subitem['label']); ?></span>
                    <?php endif; ?>
                  </div>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>
          <?php endforeach; ?>
        </div>
      </div>
    </section>
  </main>
</div>

<script>
  (function(){
    const toggles = document.querySelectorAll('[data-nav-toggle]');
    toggles.forEach(btn => {
      btn.addEventListener('click', () => {
        const group = btn.closest('.nav-group');
        if (!group) return;
        group.classList.toggle('open');
      });
    });
  })();
</script>
</body>
</html>

