<?php
require_once 'db.php';
require_once 'functions.php';


require_once 'PHPMailer/src/PHPMailer.php';
require_once 'PHPMailer/src/SMTP.php';
require_once 'PHPMailer/src/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;


if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(405, "Invalid request method.");
}

$data = json_decode(file_get_contents('php://input'), true);

// Validate required fields
if (empty($data['email']) || empty($data['new_password']) || empty($data['otp'])) {
    jsonResponse(400, "Email, OTP, and new password are required.");
}

// Decrypt inputs
$email       = decryptData($data['email']);
$newPassword = decryptData($data['new_password']);
$otp         = decryptData($data['otp']);

try {
    // Check if user with given email and OTP exists
    $stmt = $pdo->prepare("SELECT id, full_name, otp_created_at FROM kd_print_admin WHERE email = ? AND otp_code = ?");
    $stmt->execute([$email, $otp]);

    if ($stmt->rowCount() === 0) {
        jsonResponse(401, "Invalid OTP or email.");
    }

    $admin = $stmt->fetch(PDO::FETCH_ASSOC);

    // Optional: Validate OTP expiration (e.g., 10 mins)
    $otpCreatedAt = strtotime($admin['otp_created_at']);
    if (time() - $otpCreatedAt > 600) {
        jsonResponse(401, "OTP has expired.");
    }

    // Hash the new password
    $hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT);

    // Update password and clear OTP fields
    $update = $pdo->prepare("UPDATE kd_print_admin SET password = ?, otp_code = NULL, otp_created_at = NULL WHERE email = ?");
    $update->execute([$hashedPassword, $email]);

    // Send confirmation email
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = 'email-smtp.ap-south-1.amazonaws.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'AKIAU6GDVFKR5U5SID7X'; // Replace with your SMTP credentials
        $mail->Password   = 'BJRaGvPSP/Yc5B4SIU2dfp31U2CLjWgI48pV1mg3RZXW';
        $mail->SMTPSecure = 'tls';
        $mail->Port       = 587;

        $mail->setFrom('exam@penoft.com', 'Penoft Examination System');
        $mail->addAddress($email, $admin['full_name']);
        $mail->addBCC('abin@penoft.com');
        $mail->isHTML(true);
        $mail->Subject = 'Penoft Examination System login Password Was Changed';
        $mail->Body    = "
            <div style='font-family: Arial, sans-serif;'>
                <h2 style='color:#007bff;'>Password Changed Successfully</h2>
                <p>Hello <strong>{$admin['full_name']}</strong>,</p>
                <p>Your password for Penoft Examination system was successfully changed.</p>
                <p>If you did not initiate this change, please contact support immediately it@penoft.com </p>
                <br>
                <small style='color:gray;'>This is an automated message. Please do not reply.</small>
            </div>
        ";

        $mail->send();
    } catch (Exception $e) {
        // Log error but don’t fail password change
        error_log("Mail error: " . $mail->ErrorInfo);
    }

    jsonResponse(200, "Password updated and confirmation email sent.");
} catch (Exception $e) {
    jsonResponse(500, "Internal server error: " . $e->getMessage());
}