<?php
// Start session
session_start();

// Include database connection
require_once('../Connections/ebanking.php');

// Include PHPMailer files if not using Composer
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';

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

// Handle login form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['username'])) {
    $loginUsername = mysqli_real_escape_string($ebanking, $_POST['username']);
    $password = mysqli_real_escape_string($ebanking, $_POST['password']);

    $query = "SELECT * FROM customer WHERE accountno='$loginUsername' AND password='$password'";
    $result = mysqli_query($ebanking, $query);
    $user = mysqli_fetch_assoc($result);

    if ($user) {
        // Generate OTP code
        $otp = rand(1000, 9999);
        $_SESSION['otp'] = $otp;
        $_SESSION['accountno'] = $user['accountno'];

        // Send OTP code via email
        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host       = 'mail.al-shajarahislamicbank.com';
            $mail->SMTPAuth   = true;
            $mail->Username   = 'noreply@al-shajarahislamicbank.com';
            $mail->Password   = 'yc1]f2FqB{6J';
            $mail->SMTPSecure = 'ssl';
            $mail->Port       = 465;
            $mail->setFrom('noreply@al-shajarahislamicbank.com', 'Al Shajarah Islamic Bank');
            $mail->addAddress($user['email'], $user['accountno']);
            $mail->isHTML(true);
            $mail->Subject = 'Login OTP Code';
            $mail->Body    = '<h1>Your Secured Login OTP Code Is:</h1><br><h2>' . $otp . '</h2>';
            $mail->AltBody = 'Your OTP Code Is: ' . $otp;
            $mail->send();

            // Redirect to OTP verification page
            header("Location: otp_verification.php");
            exit();
        } catch (Exception $e) {
            echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}<br>";
        }
    } else {
        // Redirect to failed login page
        header("Location: failedlogin.php");
        exit();
    }
}
?>

<!-- HTML form -->
<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Head content -->
</head>
<body>
    <div id="content">
        <!-- Content section -->
    </div>
    <div id="jbfooter">
        <!-- Footer section -->
    </div>
</body>
</html>
