<?php

require_once __DIR__ . '/includes/settings_helpers.php';

settings_require_auth();
settings_ensure_tables($conn);

$org = settings_get_current_org($conn);
$orgId = (int) ($org['id'] ?? 0);

$featureSets = settings_subscription_feature_sets();
$coreFeatureSummary = settings_subscription_feature_text($featureSets['core']);
$premiumFeatureSummary = settings_subscription_feature_text($featureSets['premium']);

$trialEndsOn = date('Y-m-d', strtotime('+14 days'));
$columnCheck = $conn->query("SHOW COLUMNS FROM subscription_details LIKE 'premium_feature_summary'");
if ($columnCheck && $columnCheck->num_rows === 0) {
    $conn->query("ALTER TABLE subscription_details ADD COLUMN premium_feature_summary TEXT DEFAULT NULL");
}
$seed = $conn->prepare(
    "INSERT INTO subscription_details
     (organization_id, plan_name, billing_cycle, monthly_price, employee_limit, status, trial_ends_on, feature_summary, premium_feature_summary)
     VALUES (?, '14-DAYS FREE TRIAL', 'monthly', 0.00, 0, 'trial', ?, ?, ?)
     ON DUPLICATE KEY UPDATE
     trial_ends_on = COALESCE(trial_ends_on, VALUES(trial_ends_on)),
     feature_summary = COALESCE(feature_summary, VALUES(feature_summary)),
     premium_feature_summary = COALESCE(premium_feature_summary, VALUES(premium_feature_summary))"
);
if ($seed) {
    $seed->bind_param('isss', $orgId, $trialEndsOn, $coreFeatureSummary, $premiumFeatureSummary);
    $seed->execute();
    $seed->close();
}

$subscription = [
    'plan_name' => '14-DAYS FREE TRIAL',
    'monthly_price' => '0.00',
    'employee_limit' => 0,
    'status' => 'trial',
    'trial_ends_on' => $trialEndsOn,
    'feature_summary' => $coreFeatureSummary,
    'premium_feature_summary' => $premiumFeatureSummary,
];

$stmt = $conn->prepare("SELECT * FROM subscription_details WHERE organization_id = ? LIMIT 1");
if ($stmt) {
    $stmt->bind_param('i', $orgId);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result ? $result->fetch_assoc() : null;
    if ($row) {
        $subscription = array_merge($subscription, $row);
    }
    $stmt->close();
}

$employeeCount = 0;
$countResult = $conn->query("SELECT COUNT(*) AS total FROM employees WHERE is_deleted = 0");
if ($countResult) {
    $countRow = $countResult->fetch_assoc();
    $employeeCount = (int) ($countRow['total'] ?? 0);
}

$coreFeatures = settings_parse_feature_text($subscription['feature_summary'] ?? '');
$premiumFeatures = settings_parse_feature_text($subscription['premium_feature_summary'] ?? '');

$coreFeatures = settings_merge_feature_list($coreFeatures, $featureSets['core']);
$premiumFeatures = settings_merge_feature_list($premiumFeatures, $featureSets['premium']);

$isTrialPlan = strtolower((string) ($subscription['status'] ?? '')) === 'trial'
    || stripos((string) ($subscription['plan_name'] ?? ''), 'trial') !== false;
$rawEmployeeLimit = isset($subscription['employee_limit']) ? (int) $subscription['employee_limit'] : 0;
$employeeLimitLabel = $rawEmployeeLimit > 0 ? (string) $rawEmployeeLimit : '-';
$trialEndsOnLabel = !empty($subscription['trial_ends_on']) && strtotime((string) $subscription['trial_ends_on']) !== false
    ? date('d/m/Y', strtotime((string) $subscription['trial_ends_on']))
    : '--';

if ($isTrialPlan && $rawEmployeeLimit <= 0) {
    $subscription['employee_limit'] = 0;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Subscription Details | Settings</title>
  <link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
  <link rel="stylesheet" href="assets/font-inter.css">
  <link rel="stylesheet" href="orgprofile.css">
</head>
<body class="orgprofile-page">
  <?php settings_render_header($_SESSION['org_name'] ?? 'demo', 'dashboard.php', 'fa-credit-card'); ?>

  <main class="profile-layout">
    <?php settings_render_sidebar('subscriptions'); ?>

    <section class="profile-main">
      <div class="profile-head">
        <h1>Subscription Details</h1>
        <div class="toolbar-actions">
          <a class="config-link" href="#">View Feature Details</a>
          <a class="save-btn" href="#">Upgrade Plan</a>
        </div>
      </div>

      <div class="profile-card">
        <h2>Plan Details</h2>
        <div style="max-width:320px;padding:18px;border-radius:16px;background:#f5f8ff;border:1px solid #dce6ff;margin-top:16px;">
          <div class="muted" style="text-transform:uppercase;letter-spacing:.08em;">Plan Name</div>
          <div style="font-size:24px;font-weight:800;margin-top:10px;"><?php echo htmlspecialchars($subscription['plan_name']); ?></div>
          <div class="muted" style="margin-top:10px;">Status: <?php echo htmlspecialchars(ucfirst($subscription['status'])); ?></div>
          <div class="muted">
            <?php echo $isTrialPlan ? 'Trial ends on' : 'Billing cycle'; ?>:
            <?php echo htmlspecialchars($isTrialPlan ? $trialEndsOnLabel : (string) ($subscription['billing_cycle'] ?? '--')); ?>
          </div>
        </div>

        <h2 style="margin-top:32px;">Usage Stats</h2>
        <div class="contact-card" style="max-width:760px;margin-top:16px;">
          <div style="font-size:15px;font-weight:700;">Employee</div>
          <div style="display:flex;align-items:center;gap:16px;margin-top:18px;">
            <div class="contact-icon" style="background:#eef4ff;color:#2563eb;"><i class="fa-regular fa-user"></i></div>
            <div style="font-size:30px;font-weight:800;"><?php echo $employeeCount; ?></div>
            <div class="muted">/ <?php echo htmlspecialchars($employeeLimitLabel); ?> used</div>
          </div>
        </div>

        <h2 style="margin-top:32px;">Features</h2>
        <div class="contact-card" style="margin-top:16px;">
          <div style="font-size:13px;font-weight:700;text-transform:uppercase;color:#6b7280;">Core Features</div>
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px 24px;margin-top:18px;">
            <?php foreach ($coreFeatures as $feature): ?>
              <div style="display:flex;align-items:center;gap:10px;">
                <i class="fa-solid fa-circle-check" style="color:#2563eb;"></i>
                <span><?php echo htmlspecialchars($feature); ?></span>
              </div>
            <?php endforeach; ?>
          </div>
          <div style="margin-top:24px;padding-top:18px;border-top:1px solid var(--border);">
            <div style="font-size:13px;font-weight:700;text-transform:uppercase;color:#6b7280;">Premium Features</div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px 24px;margin-top:18px;">
              <?php foreach ($premiumFeatures as $feature): ?>
                <div style="display:flex;align-items:center;gap:10px;">
                  <i class="fa-solid fa-circle-check" style="color:#2563eb;"></i>
                  <span><?php echo htmlspecialchars($feature); ?></span>
                </div>
              <?php endforeach; ?>
            </div>
          </div>
        </div>
      </div>
    </section>
  </main>
</body>
</html>
