<?php
include "db.php";

// ─── BASE URL ─────────────────────────────────────────────────────────────────
$base_url = strtok($_SERVER['REQUEST_URI'], '?');

$page_param = !empty($_GET['page']) ? $_GET['page'] : '';

function build_url_m($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');
}

$month_key = $selected_month; // stored as YYYY-MM

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

    $mk           = mysqli_real_escape_string($conn, $month_key);
    $sales        = floatval($_POST['sales']              ?? 0);
    $fg_movement  = floatval($_POST['fg_movement']        ?? 0);
    $rev_std_hrs  = floatval($_POST['rev_per_std_hours']  ?? 0);
    $working_days = intval($_POST['working_days']         ?? 0);
    $no_directs   = intval($_POST['no_of_directs']        ?? 0);
	$no_tpl_directs = intval($_POST['purchase_overspend'] ?? 0);

    $check = mysqli_query($conn,
        "SELECT id FROM monthly_kpi WHERE month_key = '$mk' LIMIT 1"
    );

    if ($check && mysqli_num_rows($check) > 0) {
        $row = mysqli_fetch_assoc($check);
        mysqli_query($conn,
            "UPDATE monthly_kpi SET
                sales             = $sales,
                fg_movement       = $fg_movement,
                rev_per_std_hours = $rev_std_hrs,
                working_days      = $working_days,
                no_of_directs      = $no_directs,
                purchase_overspend  = $no_tpl_directs
             WHERE id = " . intval($row['id'])
        );
    } else {
        mysqli_query($conn,
            "INSERT INTO monthly_kpi
                (month_key, sales, fg_movement, rev_per_std_hours, working_days, no_of_directs, purchase_overspend)
             VALUES
                ('$mk', $sales, $fg_movement, $rev_std_hrs, $working_days, $no_directs, $no_tpl_directs)"
        );
    }

    header("Location: " . build_url_m($base_url, ['month' => $selected_month, 'saved' => '1']));
    exit;
}

// ─── FETCH DATA FOR SELECTED MONTH ───────────────────────────────────────────
$mk_esc = mysqli_real_escape_string($conn, $month_key);
$result = mysqli_query($conn,
    "SELECT * FROM monthly_kpi WHERE month_key = '$mk_esc' LIMIT 1"
);

$kpi = [];
if ($result && mysqli_num_rows($result) > 0) {
    $kpi = mysqli_fetch_assoc($result);
}

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

// ─── MONTH NAV ────────────────────────────────────────────────────────────────
$prev_month    = date('Y-m', strtotime($month_key . '-01 -1 month'));
$next_month    = date('Y-m', strtotime($month_key . '-01 +1 month'));
$display_month = date('F Y', strtotime($month_key . '-01'));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Monthly 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:120px; }

  /* Field cards for single-row layout */
  .field-card {
    background:#f8f9fa;
    border:1px solid #e0e4ea;
    border-radius:10px;
    padding:18px 20px;
    flex:1 1 160px;
    min-width:160px;
  }
  .field-card label {
    font-size:.78rem;
    font-weight:600;
    color:#6c757d;
    text-transform:uppercase;
    letter-spacing:.04em;
    margin-bottom:8px;
    display:block;
  }
  .field-card .field-icon {
    font-size:1.4rem;
    margin-bottom:6px;
    display:block;
  }
</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">📅 Monthly KPI Management</h4>

    <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>

    <div class="d-flex gap-2">
      <a href="<?= htmlspecialchars(build_url_m($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_m($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">
      ✅ Monthly 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 monthly KPI data found for <strong><?= htmlspecialchars($display_month) ?></strong>.
      Fill in the fields below and click <strong>Save KPI</strong>.
    </div>
  <?php endif; ?>

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

    <form method="POST"
          action="<?= htmlspecialchars(build_url_m($base_url, ['month' => $selected_month])) ?>">

      <div class="d-flex flex-wrap gap-3 mb-4">

        <!-- Sales -->
        <div class="field-card">
          <span class="field-icon">💷</span>
          <label for="sales">Sales £</label>
          <input type="number" step="0.01" id="sales" name="sales"
                 class="form-control"
                 value="<?= htmlspecialchars($kpi['sales'] ?? '') ?>"
                 placeholder="0.00">
        </div>

        <!-- FG Movement -->
        <div class="field-card">
          <span class="field-icon">📦</span>
          <label for="fg_movement">FG Movement £</label>
          <input type="number" step="0.01" id="fg_movement" name="fg_movement"
                 class="form-control"
                 value="<?= htmlspecialchars($kpi['fg_movement'] ?? '') ?>"
                 placeholder="0.00">
        </div>

        <!-- Revenue per Std Hours -->
        <div class="field-card">
          <span class="field-icon">⏱️</span>
          <label for="rev_per_std_hours">Revenue per Std Hrs £</label>
          <input type="number" step="0.0001" id="rev_per_std_hours" name="rev_per_std_hours"
                 class="form-control"
                 value="<?= htmlspecialchars($kpi['rev_per_std_hours'] ?? '') ?>"
                 placeholder="0.0000">
        </div>

        <!-- Working Days -->
        <div class="field-card">
          <span class="field-icon">📆</span>
          <label for="working_days">Working Days</label>
          <input type="number" step="1" min="0" max="31" id="working_days" name="working_days"
                 class="form-control"
                 value="<?= htmlspecialchars($kpi['working_days'] ?? '') ?>"
                 placeholder="0">
        </div>

        <!-- No. of Directs -->
        <div class="field-card">
          <span class="field-icon">👷</span>
          <label for="no_of_directs">No. of Directs</label>
          <input type="number" step="1" min="0" id="no_of_directs" name="no_of_directs"
                 class="form-control"
                 value="<?= htmlspecialchars($kpi['no_of_directs'] ?? '') ?>"
                 placeholder="0">
        </div>
		<!-- No. of TPL Directs -->
		<div class="field-card">
		  <span class="field-icon">-</span>
		  <label for="purchase_overspend">Minus Over Spend</label>

		  <input type="number"
				 step="1"
				 min="0"
				 id="purchase_overspend"
				 name="purchase_overspend"
				 class="form-control"
				 value="<?= htmlspecialchars($kpi['purchase_overspend'] ?? '') ?>"
				 placeholder="0">
		</div>

      </div>

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

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