<?php
session_start();
require_once '../../includes/db_connect.php';
require '../../vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $student_id = isset($_POST['student_id']) ? trim($_POST['student_id']) : '';
if (empty($email) || empty($student_id)) {
    die("이메일과 학번을 모두 입력해주세요.");
}
    $stmt = $conn->prepare("SELECT id FROM Users WHERE email = ? AND student_id = ?");
    $stmt->bind_param("ss", $email, $student_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();

    if (!$user) {
        die("이메일 또는 학번이 올바르지 않습니다.");
    }

    $user_id = $user['id'];
    $code = rand(100000, 999999);
    $hashed_code = password_hash((string)$code, PASSWORD_DEFAULT);

    $expires_at = (new DateTime('+30 minutes'))->format('Y-m-d H:i:s');

    $stmt = $conn->prepare("INSERT INTO Password_reset_codes (user_id, code, expires_at) VALUES (?, ?, ?)");
    $stmt->bind_param("iss", $user_id, $hashed_code, $expires_at);
    $stmt->execute();

    $mail = new PHPMailer(true);
    try {
        $mail->CharSet = 'UTF-8';
        $mail->ContentType = 'text/html; charset=UTF-8';
        $mail->Encoding = 'base64';
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'kyc080418@gmail.com';
        $mail->Password = 'atbdmelxcbefrxcb'; // 실제 앱 비밀번호
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;

        $mail->setFrom('kyc080418@gmail.com', 'M-Order 관리자');
        $mail->addAddress($email);
        $mail->isHTML(true);
        $mail->Subject = '비밀번호 재설정 인증코드';
        $mail->Body = "
            안녕하세요,<br><br>
            아래 인증코드를 입력하여 비밀번호 재설정을 진행해주세요.<br><br>
            <h2 style='color:#2c3e50;'>$code</h2><br>
            이 코드는 <strong>30분간</strong> 유효합니다.<br><br>
            감사합니다.
        ";

        $mail->send();
        header("Location: /Capstone/auth/enter-code.php?user_id=$user_id");
        exit;
    } catch (Exception $e) {
        die("메일 전송 실패: {$mail->ErrorInfo}");
    }
}
?>
