<?php
include "db.php";

$days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];

// ─── BASE URL: keep ?page=add (or any persistent params) ─────────────────────
$base_url = strtok($_SERVER['REQUEST_URI'], '?');

// ─── PRESERVE page= param so links/redirects stay on the right route ─────────
$page_param = !empty($_GET['page']) ? $_GET['page'] : '';

// Helper: builds a query string always including page= if present
function build_url($base, $params = []) {
    global $page_param;
    if ($page_param !== '') {
        $params['page'] = $page_param;
    }
    return $base . '?' . http_build_query($params);
}

// ─── SELECTED MONTH ───────────────────────────────────────────────────────────
if (!empty($_GET['month']) && preg_match('/^\d{4}-\d{2}$/', $_GET['month'])) {
    $selected_month = $_GET['month'];
} else {
    $selected_month = date('Y-m');
}

$week_start_key = $selected_month . '-01';

// ─── SAVE / UPDATE ────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {

    $ws = mysqli_real_escape_string($conn, $week_start_key);

    foreach ($days as $d) {
        $production_target = floatval($_POST['production_target'][$d] ?? 0);
        $std_hours         = floatval($_POST['std_hours'][$d]         ?? 0);
        $sales_target      = floatval($_POST['sales_target'][$d]      ?? 0);
        $fg_contribution   = floatval($_POST['fg_contribution'][$d]   ?? 0);
        $clock_hours       = floatval($_POST['clock_hours'][$d]       ?? 0);
        $productivity      = mysqli_real_escape_string($conn, trim($_POST['productivity'][$d] ?? ''));
        $day_name          = mysqli_real_escape_string($conn, $d);

        $check = mysqli_query($conn,
            "SELECT id FROM weekly_kpi
             WHERE week_start = '$ws' AND day_name = '$day_name'
             LIMIT 1"
        );

        if ($check && mysqli_num_rows($check) > 0) {
            $row = mysqli_fetch_assoc($check);
            mysqli_query($conn,
                "UPDATE weekly_kpi SET
                    production_target = $production_target,
                    std_hours         = $std_hours,
                    sales_target      = $sales_target,
                    fg_contribution   = $fg_contribution,
                    clock_hours       = $clock_hours,
                    productivity      = '$productivity'
                 WHERE id = " . intval($row['id'])
            );
        } else {
            mysqli_query($conn,
                "INSERT INTO weekly_kpi
                    (week_start, day_name, production_target, std_hours,
                     sales_target, fg_contribution, clock_hours, productivity)
                 VALUES
                    ('$ws','$day_name',$production_target,$std_hours,
                     $sales_target,$fg_contribution,$clock_hours,'$productivity')"
            );
        }
    }

    // ✅ FIX: redirect preserves ?page=add&month=...&saved=1
    header("Location: " . build_url($base_url, ['month' => $selected_month, 'saved' => '1']));
    exit;
}

// ─── FETCH DATA FOR SELECTED MONTH ───────────────────────────────────────────
$ws_esc = mysqli_real_escape_string($conn, $week_start_key);
$result = mysqli_query($conn,
    "SELECT * FROM weekly_kpi
     WHERE week_start = '$ws_esc'
     ORDER BY FIELD(day_name,'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday')"
);

$kpi_data = [];
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $kpi_data[$row['day_name']] = $row;
    }
}

$has_data   = !empty($kpi_data);
$show_saved = isset($_GET['saved']);

// ─── MONTH NAV ────────────────────────────────────────────────────────────────
$prev_month    = date('Y-m', strtotime($week_start_key . ' -1 month'));
$next_month    = date('Y-m', strtotime($week_start_key . ' +1 month'));
$display_month = date('F Y', strtotime($week_start_key));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Weekly KPI Management</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
<style>
  body         { background:#f4f6fb; }
  .kpi-card    { background:#fff; border-radius:12px; box-shadow:0 2px 12px rgba(0,0,0,.08); padding:28px; }
  thead th     { background:#2c3e50; color:#fff; white-space:nowrap; }
  .no-data-box { background:#fff3cd; border-left:4px solid #ffc107; padding:13px 18px; border-radius:6px; }
  .saved-box   { background:#d1e7dd; border-left:4px solid #198754; padding:13px 18px; border-radius:6px; }
  input.form-control { min-width:100px; }
</style>
</head>
<body class="p-3 p-md-4">
<div class="container-xl">

  <!-- ── Top bar ── -->
  <div class="kpi-card mb-4 d-flex flex-wrap align-items-center justify-content-between gap-3">
    <h4 class="mb-0">📊 Weekly KPI Management</h4>

    <!-- ✅ FIX: Month jump form includes hidden page param -->
    <form method="GET" action="<?= htmlspecialchars($base_url) ?>" class="d-flex align-items-center gap-2">
      <?php if ($page_param !== ''): ?>
        <input type="hidden" name="page" value="<?= htmlspecialchars($page_param) ?>">
      <?php endif; ?>
      <label class="mb-0 fw-semibold small">Month:</label>
      <input type="month" name="month" value="<?= htmlspecialchars($selected_month) ?>"
             class="form-control form-control-sm" style="width:160px">
      <button class="btn btn-primary btn-sm">Go</button>
    </form>

    <!-- ✅ FIX: Prev/Next links include page= param -->
    <div class="d-flex gap-2">
      <a href="<?= htmlspecialchars(build_url($base_url, ['month' => $prev_month])) ?>"
         class="btn btn-outline-secondary btn-sm">&#8592; <?= date('M Y', strtotime($prev_month.'-01')) ?></a>
      <a href="<?= htmlspecialchars(build_url($base_url, ['month' => $next_month])) ?>"
         class="btn btn-outline-secondary btn-sm"><?= date('M Y', strtotime($next_month.'-01')) ?> &#8594;</a>
    </div>
  </div>

  <!-- ── Alerts ── -->
  <?php if ($show_saved): ?>
    <div class="saved-box mb-3">
      ✅ KPI data for <strong><?= htmlspecialchars($display_month) ?></strong> saved / updated successfully.
    </div>
  <?php endif; ?>

  <?php if (!$has_data && !$show_saved): ?>
    <div class="no-data-box mb-3">
      ⚠️ No KPI data found for <strong><?= htmlspecialchars($display_month) ?></strong>.
      Fill in the table below and click <strong>Save KPI</strong>.
    </div>
  <?php endif; ?>

  <!-- ── KPI Form ── -->
  <div class="kpi-card">
    <h5 class="mb-3">
      <?= $has_data ? '✏️ Update' : '➕ Add' ?> KPI —
      <span class="text-primary"><?= htmlspecialchars($display_month) ?></span>
    </h5>

    <!-- ✅ FIX: form action preserves ?page=add&month=... -->
    <form method="POST"
          action="<?= htmlspecialchars(build_url($base_url, ['month' => $selected_month])) ?>">

      <div class="table-responsive">
        <table class="table table-bordered align-middle mb-3">
          <thead>
            <tr>
              <th>Day</th>
              <th>Production Target £</th>
              <th>Std Hours</th>
              <th>Sales Target £</th>
              <th>FG Contribution £</th>
              <th>Clock Hours</th>
              <th>Productivity %</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($days as $d):
            $r = $kpi_data[$d] ?? [];
          ?>
          <tr>
            <td class="fw-semibold text-nowrap"><?= $d ?></td>
            <td><input type="number" step="0.01" name="production_target[<?= $d ?>]"
                 class="form-control" value="<?= htmlspecialchars($r['production_target'] ?? '') ?>"></td>
            <td><input type="number" step="0.01" name="std_hours[<?= $d ?>]"
                 class="form-control" value="<?= htmlspecialchars($r['std_hours'] ?? '') ?>"></td>
            <td><input type="number" step="0.01" name="sales_target[<?= $d ?>]"
                 class="form-control" value="<?= htmlspecialchars($r['sales_target'] ?? '') ?>"></td>
            <td><input type="number" step="0.01" name="fg_contribution[<?= $d ?>]"
                 class="form-control" value="<?= htmlspecialchars($r['fg_contribution'] ?? '') ?>"></td>
            <td><input type="number" step="0.0001" name="clock_hours[<?= $d ?>]"
                 class="form-control" value="<?= htmlspecialchars($r['clock_hours'] ?? '') ?>"></td>
            <td><input type="text" name="productivity[<?= $d ?>]"
                 class="form-control" value="<?= htmlspecialchars($r['productivity'] ?? '') ?>"></td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <button type="submit" name="submit" class="btn btn-success px-5">
        <?= $has_data ? '💾 Update KPI' : '✅ Save KPI' ?>
      </button>
    </form>
  </div>

</div>
</body>
</html>