<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

// Include PHPMailer
require_once __DIR__ . '/../lib/PHPMailer/src/PHPMailer.php';
require_once __DIR__ . '/../lib/PHPMailer/src/SMTP.php';
require_once __DIR__ . '/../lib/PHPMailer/src/Exception.php';

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

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);

    // Fetch user by username
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && password_verify($password, $user['password_hash'])) {
        // Generate OTP
        $otp = random_int(100000, 999999); // 6-digit OTP
        $_SESSION['otp'] = $otp;
        $_SESSION['otp_user_id'] = $user['id'];
        $_SESSION['otp_expires'] = time() + 300; // OTP valid for 5 minutes

        // Send OTP email
        try {
            $mail = new PHPMailer(true);
            $mail->isSMTP();
            $mail->Host       = $_ENV['BREVO_SMTP_HOST'];
            $mail->SMTPAuth   = true;
            $mail->Username   = $_ENV['BREVO_SMTP_USER'];
            $mail->Password   = $_ENV['BREVO_SMTP_PASS'];
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port       = (int)$_ENV['BREVO_SMTP_PORT'];

            $mail->setFrom($_ENV['BREVO_FROM_EMAIL'], $_ENV['BREVO_FROM_NAME']);
            $mail->addAddress($user['email'], $user['username']);

            $mail->isHTML(true);
            $mail->Subject = "Your OTP for Custora CRM Login";
            $mail->Body = "
                Hello {$user['username']},<br><br>
                You are attempting to log in to <a href='https://custora.digivortlimited.com' target='_blank'>Custora CRM</a>.<br>
                Your One-Time Password (OTP) is: <strong>{$otp}</strong><br>
                This code is valid for 5 minutes.<br><br>
                If you did not request this, please contact the system administrator immediately.<br><br>
                Best regards,<br>
                Custora CRM Support<br>
                Digital Vortex Technologies Limited
            ";
            $mail->AltBody = strip_tags($mail->Body);
            $mail->send();

            // Redirect to OTP verification page
            header("Location: otp_verify.php");
            exit;

        } catch (Exception $e) {
            $message = "Failed to send OTP. Error: " . $mail->ErrorInfo;
        }
    } else {
        $message = 'Invalid username or password';
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CRM Login</title>
<link rel="icon" href="../public/assets/img/custora_logo.png" type="image/png">
<style>
body {
    font-family: Arial, sans-serif;
    background: #f4f7fa;
    margin: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    padding: 10px;
    box-sizing: border-box;
}
.login-container {
    background: #fff;
    padding: 35px;
    width: 100%;
    max-width: 400px;
    border-radius: 10px;
    box-shadow: 0 6px 18px rgba(0,0,0,0.1);
    text-align: center;
}
.login-container h2 { margin-bottom: 20px; color: #005f8d; }
form { text-align: left; }
label { display: block; margin-bottom: 6px; font-weight: bold; color: #444; }
input[type="password"] {
    width: 95%;
    padding: 10px;
    margin-bottom: 18px;
    border: 1px solid #ccc;
    border-radius: 6px;
    outline: none;
    font-size: 14px;
}
input[type="text"]:focus, input[type="password"]:focus {
    border-color: #005f8d;
    box-shadow: 0 0 5px rgba(0,95,141,0.3); min-width: 300px;
}
button, .btn-link {
    width: 100%;
    padding: 12px;
    border: none;
    border-radius: 6px;
    font-size: 16px;
    cursor: pointer;
    margin-bottom: 15px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    transition: background 0.3s;
}
button { background: #005f8d; color: #fff; min-width: 320px;}
button:hover { background: #004466; }
.btn-link { background: #17a2b8; color: #fff; min-width: 300px; width:94%}
.btn-link:hover { background: #005f8d; }
.error {
    background: #f8d7da;
    color: #842029;
    padding: 10px;
    border-radius: 6px;
    margin-bottom: 15px;
    font-size: 14px;
    text-align: center;
}
img { width: 100%; max-width: 180px; height: auto; margin-bottom: 15px; }
/* Responsive Design */
@media (max-width: 500px) {
    .login-container { padding: 25px 20px; }
    h2 { font-size: 20px; }
    button { font-size: 15px; padding: 10px; width: 100%}
    .btn-link 
    input[type="text"] { width: 93%;} 
    input[type="password"] { width: 93%;}
}
</style>
</head>
<body>
<div class="login-container">
    <h1><img src="../public/assets/img/custora_logo.png" alt="Custora CRM"></h1>
    <h2>Login form</h2>
    <?php if ($message): ?>
        <p class="error"><?= htmlspecialchars($message) ?></p>
    <?php endif; ?>
    <form method="POST">
        <label>Username:</label>
        <input style="min-width: 300px; width: 95%; height: auto;  padding: 10px; margin-bottom: 18px; border: 1px solid #ccc; border-radius: 6px; outline: none; font-size: 14px;" "text" name="username" placeholder="Enter your username" required>
        <label>Password:</label>
        <input type="password" name="password" placeholder="Enter your password" required>
        <button type="submit">Login</button>
        <a href="../" class="btn-link">Back to Dashboard</a>
        <a href="forgot_password.php" class="btn-link">Forgot Password?</a>
    </form>
</div>
</body>
</html>