<?php

header('Content-Type: application/json');

if (session_status() === PHP_SESSION_NONE) session_start();

require_once '../config.php';



$response = ['success' => false, 'message' => ''];



if ($_SERVER['REQUEST_METHOD'] !== 'POST') { 

    echo json_encode(['success' => false, 'message' => 'Invalid request']);

    exit;

}



$username = trim($_POST['username'] ?? '');

if (empty($username)) {

    echo json_encode(['success' => false, 'message' => 'Please enter your username']);

    exit;

}



// Rate-limit: max 3 OTP requests per 10 minutes per username

$rate_key = 'otp_attempts_' . md5($username);

$attempts = $_SESSION[$rate_key]['count'] ?? 0;

$first_attempt = $_SESSION[$rate_key]['since'] ?? 0;

if (time() - $first_attempt < 600 && $attempts >= 3) {

    echo json_encode(['success' => false, 'message' => 'Too many attempts. Please wait 10 minutes and try again.']);

    exit;

}



try {

    $conn = getDBConnection();

    $stmt = $conn->prepare("SELECT id, full_name, phone FROM users WHERE username = ? AND (is_active IS NULL OR is_active = 1) LIMIT 1");

    $stmt->bind_param('s', $username);

    $stmt->execute();

    $user = $stmt->get_result()->fetch_assoc();

    $stmt->close();



    if (!$user) {

        // Return success anyway to prevent username enumeration

        echo json_encode(['success' => true, 'message' => 'If that username exists, an OTP has been sent.', 'masked_phone' => '']);

        exit;

    }



    $phone = trim($user['phone'] ?? '');

    if (empty($phone)) {

        echo json_encode(['success' => false, 'message' => 'No phone number is linked to this account. Please contact your administrator to reset your password.']);

        exit;

    }



    // Generate 6-digit OTP

    $otp = str_pad((string) random_int(100000, 999999), 6, '0', STR_PAD_LEFT);



    // Store in session (expires in 10 minutes)

    $_SESSION['pwd_reset'] = [

        'otp'     => password_hash($otp, PASSWORD_BCRYPT),

        'user_id' => (int) $user['id'],

        'expires' => time() + 600,

    ];



    // Update rate-limit counter

    if (time() - $first_attempt >= 600) {

        $_SESSION[$rate_key] = ['count' => 1, 'since' => time()];

    } else {

        $_SESSION[$rate_key]['count'] = $attempts + 1;

    }



    // Send SMS

    $name = explode(' ', $user['full_name'])[0];

    $message = "EduTrack: Hi $name, your password reset code is $otp. Valid for 10 minutes. Do not share this code.";

    sendSMS($phone, $message);



    // Mask phone: show first 3 and last 2 digits

    $masked = substr($phone, 0, 3) . str_repeat('*', max(0, strlen($phone) - 5)) . substr($phone, -2);



    echo json_encode(['success' => true, 'message' => 'OTP sent', 'masked_phone' => $masked]);



} catch (Exception $e) {

    error_log('send_reset_otp: ' . $e->getMessage());

    echo json_encode(['success' => false, 'message' => 'An error occurred. Please try again.']);

}

