<?php
// reset-password-handler.php — POST handler for reset-password.php
//
// Validates the session-carried email, hashes the new password,
// updates the users table, clears reset session vars, and redirects
// to signin.php with a success flash message.

session_start();
require_once __DIR__ . '/config/db.php';

/**
 * Abort back to reset-password.php with an error flash.
 */
function back_with_error(string $msg): never
{
    $_SESSION['reset_error'] = $msg;
    header('Location: reset-password.php');
    exit;
}

// Only POST is allowed.
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: reset-password.php');
    exit;
}

// Guard: email must have been verified via OTP in this session.
$email = $_SESSION['reset_email'] ?? '';
if ($email === '' || empty($_SESSION['reset_email_verified'])) {
    header('Location: forgot-password.php');
    exit;
}

// Collect and validate inputs.
$password = (string) ($_POST['password'] ?? '');
$confirm  = (string) ($_POST['confirm']  ?? '');

if ($password === '' || $confirm === '') {
    back_with_error('Please fill in both password fields.');
}

if (strlen($password) < 8) {
    back_with_error('Password must be at least 8 characters long.');
}

if ($password !== $confirm) {
    back_with_error('Passwords do not match. Please try again.');
}

// Verify the account still exists and belongs to a customer.
$stmt = $conn->prepare(
    "SELECT id, status FROM users WHERE email = ? AND role = 'customer' LIMIT 1"
);
$stmt->bind_param('s', $email);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user) {
    // Edge case: account deleted after OTP was issued.
    unset($_SESSION['reset_email'], $_SESSION['reset_email_verified'], $_SESSION['reset_error']);
    $_SESSION['login_error'] = 'Account not found. Please sign up or contact support.';
    header('Location: signin.php');
    exit;
}

if ((int) $user['status'] !== 1) {
    back_with_error('Your account is inactive. Please contact support.');
}

// Hash and save the new password.
$hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);

$update = $conn->prepare('UPDATE users SET password = ? WHERE id = ?');
$update->bind_param('si', $hash, $user['id']);

if (!$update->execute() || $update->affected_rows < 1) {
    back_with_error('Something went wrong saving your password. Please try again.');
}

// Clean up all reset-related session data.
unset(
    $_SESSION['reset_email'],
    $_SESSION['reset_email_verified'],
    $_SESSION['reset_error']
);

// Redirect to sign-in with a success message.
$_SESSION['login_success'] = 'Password updated! Please log in with your new password.';
header('Location: signin.php');
exit;
