<?php
// login.php

// ---------------
// 1) INCLUDES & SETUP
// ---------------
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require './mail/Exception.php';   // Pastikan path sesuai
require './mail/PHPMailer.php';
require './mail/SMTP.php';

require 'security.php';
require 'logger.php';
require 'rate_limit.php';
require 'db.php';  // Koneksi $pdo

header("Content-Type: application/json; charset=UTF-8");

// ---------------
// 2) METHOD CHECK & RATE LIMIT
// ---------------
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    log_activity("Method Not Allowed on login.php from IP: " . $_SERVER['REMOTE_ADDR']);
    exit;
}

// Terapkan rate limiting (misal, 5 request per menit)
$identifier = $_SERVER['REMOTE_ADDR'] . ':' . $_SERVER['REQUEST_URI'];
rate_limit($pdo, 5, 60, $identifier); // max_requests=5, time_window=60 detik

// ---------------
// 3) AMBIL INPUT
// ---------------
$input_raw = file_get_contents('php://input');
$input = json_decode($input_raw, true);

// Sanitasi input (pastikan fungsi sanitize_input ada)
$input = sanitize_input($input);

// Validasi input
if (empty($input['email']) || empty($input['password'])) {
    http_response_code(400);
    echo json_encode(['error' => 'email and password are required']);
    log_activity("Missing fields in login from IP: " . $_SERVER['REMOTE_ADDR']);
    exit;
}

$email    = $input['email'];
$password = $input['password'];

// Validasi format email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid email format']);
    log_activity("Invalid email format '$email' in login.");
    exit;
}

// ---------------
// 4) VALIDASI USER & PASSWORD
// ---------------
try {
    // Cek jika akun adalah akun demo
    if ($email === 'admin@demo.com') {
        if ($password === 'abcABC1$') {
            // Jika password benar, langsung kirim OTP 888888 tanpa simpan ke DB
            http_response_code(200);
            echo json_encode([
                'message'        => 'Demo login successful',
                'info'           => 'Use OTP 888888',
                'otp_expiration' => date('Y-m-d H:i:s', time() + (30 * 60))
            ]);
            log_activity("Demo user '$email' logged in, OTP: 888888");
            exit;
        } else {
            http_response_code(401);
            echo json_encode(['error' => 'Invalid credentials']);
            log_activity("Invalid login attempt for demo account.");
            exit;
        }
    }

    // Cari user di DB
    $stmt = $pdo->prepare("SELECT id, password, role FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if (!$user) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid credentials']);
        log_activity("Invalid login attempt for email '$email'.");
        exit;
    }

    // Verifikasi password
    if (!password_verify($password, $user['password'])) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid credentials']);
        log_activity("Invalid password attempt for email '$email'.");
        exit;
    }

    // --------------- 
    // 5) GENERATE OTP & SIMPAN (HASH) 
    // ---------------
    $plaintextOTP = mt_rand(100000, 999999);
    $hashedOTP = md5($plaintextOTP);
    $expiresAt = date('Y-m-d H:i:s', time() + (30 * 60));

    // Simpan OTP di database
    $stmt = $pdo->prepare("INSERT INTO otps (user_id, otp_code, expires_at) VALUES (?, ?, ?)");
    $stmt->execute([$user['id'], $hashedOTP, $expiresAt]);

    // --------------- 
    // 6) KIRIM OTP KE EMAIL 
    // ---------------
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = 'mail.kopmandan.com'; 
        $mail->SMTPAuth   = true;
        $mail->Username   = 'admin@kopmandan.com';
        $mail->Password   = 'f2K7ToyDZrUQ';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;

        $mail->setFrom('admin@kopmandan.com', 'Koperasi Komandan');
        $mail->addAddress($email, 'User');

        $mail->isHTML(true);
        $mail->Subject = 'Kode Verifikasi Anda';
        $validUntil = date('d F Y, H:i', strtotime($expiresAt)) . ' WIB';
        $mail->Body    = "
            <p>Salam,</p>
            <p>Berikut adalah kode OTP Anda:</p>
            <h2 style='text-align:center;'>$plaintextOTP</h2>
            <p>Kode ini berlaku hingga <strong>$validUntil</strong> (30 menit).</p>
            <p>Jika Anda tidak merasa melakukan login, abaikan email ini.</p>
        ";

        $mail->send();

        // --------------- 
        // 7) RESPONSE (SUKSES) 
        // ---------------
        http_response_code(200);
        echo json_encode([
            'message'        => 'OTP sent to your email',
            'info'           => 'Check your inbox for the OTP code',
            'otp_expiration' => $expiresAt
        ]);
        log_activity("User '$email' passed password check. OTP generated & emailed.");

    } catch (Exception $e) {
        // Jika gagal kirim email
        $error = "Email error: " . $mail->ErrorInfo;
        http_response_code(500);
        echo json_encode(['error' => $error]);
        log_activity("login.php mail sending error: $error");
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
    log_activity("login.php server error: " . $e->getMessage());
    exit;
}
