<?php

function abs_url($path) {
    if (!$path) return '';
    $isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
    // already absolute?
    if (preg_match('#^https?://#i', $path)) {
        return $isHttps ? preg_replace('#^http://#i','https://',$path) : $path;
    }

    // ensure /sbm prefix when missing
    if ($path[0] === '/') {
        if (strpos($path, '/sbm/') !== 0) {
            $path = '/sbm' . $path; // ← your site lives under /sbm
        }
    } else {
        // relative like "uploads/..": anchor to current script dir
        $base = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/'); // e.g. /sbm/public
        $path = $base . '/' . ltrim($path, '/');
    }

    $scheme = $isHttps ? 'https' : 'http';
    $host   = $_SERVER['HTTP_HOST'] ?? '';
    return "$scheme://$host$path";
}

require __DIR__ . '/../includes/db.php';
require __DIR__ . '/../includes/helpers.php';

$phone = preg_replace('/[^0-9]/','', $_GET['phone'] ?? '');
if (strlen($phone) !== 10) json_response(['found'=>false, 'message'=>'invalid phone']);

$stmt = $pdo->prepare('SELECT * FROM residents WHERE phone = :phone LIMIT 1');
$stmt->execute(['phone'=>$phone]);
$res = $stmt->fetch();
if (!$res) json_response(['found'=>false]);

$stmt2 = $pdo->prepare('SELECT training_number, waste_segregation, door_to_door, photo_path, training_date, created_at
                        FROM trainings WHERE resident_id = :rid ORDER BY training_number ASC');

$stmt2->execute(['rid'=>$res['id']]);
$trainings = $stmt2->fetchAll();

$tc = (int)$res['trainings_completed'];
$next_num = ($tc >= 3) ? null : ($tc + 1);
$next_label = 'All trainings completed';
if ($next_num === 2) $next_label = 'Training Second';
if ($next_num === 3) $next_label = 'Training Third';

$has_training1 = false;
foreach ($trainings as $t) {
  if ((int)$t['training_number'] === 1) { $has_training1 = true; break; }
}

json_response([
  'found' => true,
  'data' => [
    'id' => (int)$res['id'],
    'ward' => $res['ward'],
    'house_no' => $res['house_no'],
    'name' => $res['name'],
    'phone' => $res['phone'],
    'waste_segregation' => $res['waste_segregation'],
    'door_to_door' => $res['door_to_door'],              // ✅ add
    'photo_path' => $res['photo_path'],
    'trainings_completed' => $tc
  ],
  'trainings' => $trainings,
  
  // ✅ ADD THESE:
  'next_training_number' => $next_num,
  'next_training_label'  => $next_label,
]);

