<?php
header("Content-Type: application/json");

require_once('config/koneksi.php');

// 🔥 PHPMailer MANUAL
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require("PHPMailer/src/Exception.php");
require("PHPMailer/src/PHPMailer.php");
require("PHPMailer/src/SMTP.php");
$input = json_decode(file_get_contents("php://input"), true);
// ================= VALIDASI METHOD =================
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(["success"=>false,"message"=>"Method tidak valid"]);
    exit;
}


$input = json_decode(file_get_contents("php://input"), true);

$email = $_POST['email'] ?? ($input['email'] ?? '');
$email = trim($email);
$email = str_replace(["\n", "\r", "\t"], '', $email);

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode([
        "success"=>false,
        "message"=>"Email tidak valid"
    ]);
    exit;
}
// ================= RATE LIMIT =================
$ip = $_SERVER['REMOTE_ADDR'];
$limitTime = date('Y-m-d H:i:s', strtotime('-2 hours'));

$stmt = $conn->prepare("
    SELECT COUNT(*) as total 
    FROM password_resets 
    WHERE (email = ? OR ip_address = ?)
    AND created_at >= ?
");
$stmt->bind_param("sss", $email, $ip, $limitTime);
$stmt->execute();
$res = $stmt->get_result()->fetch_assoc();

if ($res['total'] >= 3) {
    echo json_encode([
        "success"=>false,
        "message"=>"Terlalu banyak percobaan, coba lagi nanti"
    ]);
    exit;
}

// ================= CEK USER =================
$stmt = $conn->prepare("SELECT id, name FROM users WHERE email=? LIMIT 1");
$stmt->bind_param("s", $email);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user) {
    echo json_encode([
        "success"=>false,
        "message"=>"Email tidak ditemukan"
    ]);
    exit;
}

// ================= GENERATE PASSWORD =================
$newPassword = substr(str_shuffle("ABCDEFGHJKLMNPQRSTUVWXYZ23456789"), 0, 8);
$hash = password_hash($newPassword, PASSWORD_BCRYPT);

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

// ================= SIMPAN LOG =================
$stmt = $conn->prepare("
    INSERT INTO password_resets (email, ip_address, created_at)
    VALUES (?, ?, NOW())
");
$stmt->bind_param("ss", $email, $ip);
$stmt->execute();

// ================= LOAD TEMPLATE =================
$templatePath = __DIR__ . '/template_lupa_password.html';

if (!file_exists($templatePath)) {
    echo json_encode([
        "success"=>false,
        "message"=>"Template email tidak ditemukan"
    ]);
    exit;
}

$template = file_get_contents($templatePath);

// REPLACE VARIABLE
$html = str_replace(
    ['{{name}}', '{{password}}', '{{year}}'],
    [$user['name'], $newPassword, date("Y")],
    $template
);

// ================= KIRIM EMAIL =================
$mail = new PHPMailer(true);

try {

    $mail->isSMTP();
    $mail->Host = 'smtp.hostinger.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'support@prodis.ajhotelsystem.com'; // 🔥 ganti
    $mail->Password = 'Cp@nels0sa';       // 🔥 ganti
    $mail->SMTPSecure = 'ssl'; // 🔥 sesuai port 465
    $mail->Port = 465;

    $mail->setFrom('support@prodis.ajhotelsystem.com', 'PRODIST');
    $mail->addAddress($email, $user['name']);

    $mail->isHTML(true);
    $mail->Subject = 'Reset Password Anda';
    $mail->Body = $html;

    $mail->send();

    echo json_encode([
        "success"=>true,
        "message"=>"Password baru telah dikirimkan ke email anda"
    ]);

} catch (Exception $e) {

    echo json_encode([
        "success"=>false,
        "message"=>"Gagal kirim email",
        "error"=>$mail->ErrorInfo
    ]);
}