<?php 
ob_start(); // Start output buffering
session_start(); 
require("header.php");
// require("../config.php"); // Ensure database connection is included

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Fetch OTP setting from the settings table
$stmt = $pdo->query("SELECT otp_status FROM settings ORDER BY id DESC LIMIT 1");
$settings = $stmt->fetch(PDO::FETCH_ASSOC);
$otp_global_status = $settings ? $settings['otp_status'] : 0; // Default to 0 if not set

// Fetch system settings
$stmt = $pdo->query("SELECT * FROM settings ORDER BY id DESC LIMIT 1");
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if ($row) {
    $cphone = $row['phone'];
    $curl = $row['url'];
    $cdomain = $row['domain'];
    $cname = $row['domain_name'];
    $cpass = $row['password'];
    $cemail = $row['email2'];
    $cright = $row['copyright'];
    $chost = $row['contact_email'];
    $cport = $row['service1'];
}

// Include PHPMailer
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';

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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    try {
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';

        // Validate input
        if (empty($email) || empty($password)) {
            echo "<script>alert('Please enter email and password.'); window.history.back();</script>";
            exit;
        }

        // Query to check user existence
        $stmt = $pdo->prepare("SELECT id, username, email, password, status FROM logins WHERE email = :email OR username = :email");
        $stmt->execute(['email' => $email]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && password_verify($password, $user['password'])) {
            if ($user['status'] == 5) {
                echo "<script>alert('Account suspended. Contact support.'); window.history.back();</script>";
                exit;
            }

            $_SESSION['email'] = $email;
            $_SESSION['otp_user_id'] = $user['id'];

            if ($otp_global_status == 1) {  
                // ✅ Generate OTP and store it
                $otp = rand(100000, 999999);
                $_SESSION['otp'] = $otp;
                $_SESSION['otp_expiry'] = time() + 300; // 5 minutes expiry
                
                // Store OTP in the database
                $updateStmt = $pdo->prepare("UPDATE logins SET otp_code = ?, otp_expires = ? WHERE id = ?");
                $updateStmt->execute([$otp, date("Y-m-d H:i:s", strtotime("+5 minutes")), $user['id']]);

                // Send OTP via email
                $mail = new PHPMailer(true);
                try {
                    $mail->isSMTP();
                    $mail->Host = $chost;
                    $mail->SMTPAuth = true;
                    $mail->Username = $cemail;
                    $mail->Password = $cpass;
                    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                    $mail->Port = $cport;
                    $mail->setFrom($cemail, $cname);
                    $mail->addReplyTo($cemail, $cname);
                    $mail->addAddress($user['email']);
                    $mail->isHTML(true);
                    $mail->Subject = 'Your OTP Code';
                    $mail->Body = "<h2>Your OTP Code: <b>$otp</b></h2><p>This code expires in 5 minutes.</p>";

                    if ($mail->send()) {
                        echo "<script>alert('OTP sent successfully! Redirecting...'); window.location.href='otp_verification.php';</script>";
                        exit;
                    } else {
                        echo "<script>alert('Failed to send OTP email.'); window.history.back();</script>";
                        exit;
                    }
                } catch (Exception $e) {
                    echo "<script>alert('OTP email error: " . $mail->ErrorInfo . "'); window.history.back();</script>";
                    exit;
                }
            } 
        
        
        
        
        // Store session data after successful login
$_SESSION['SESS_LOGGEDIN'] = true;
$_SESSION['SESS_USERID'] = $user['id'];  // ✅ Use this instead of 'user_id'
$_SESSION['SESS_USERNAME'] = $user['username']; // (Optional) Store username

if ($otp_global_status == 1) {  
    // If OTP is enabled, redirect to OTP verification page
    $_SESSION['otp'] = $otp;
    $_SESSION['otp_expiry'] = time() + 300; // 5 minutes expiry
    echo "<script>alert('OTP sent successfully! Redirecting...'); window.location.href='otp_verification.php';</script>";
    exit;
} else {  
    // If OTP is disabled, log in the user directly
    echo "<script>alert('Login successful! Redirecting...'); window.location.href='../accounts/index.php';</script>";
    exit;
}
    
            
            
            
        } else {
            echo "<script>alert('Invalid email/username or password.'); window.history.back();</script>";
            exit;
        }
    } catch (Exception $e) {
        echo "<script>alert('An error occurred: " . $e->getMessage() . "'); window.history.back();</script>";
        exit;
    }
}
?>



<body>
    <!-- Account Section -->
    <section class="account-section position-relative">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-xl-6 col-lg-7 col-md-8">
                    <a href="../index.php" class="text-center d-block mb-3 mb-sm-4 auth-page-logo">
                        <img src="../<?php echo $LOGO ?>" alt="LOGO" 
     style="max-width:100%; height:auto; display:block; margin:0 auto;">

                        
                        
                          <style>
                        #yt-widget .yt-listbox__col {
                            display: block !important; /* display: inline-block; */
                            list-style: none;
                            vertical-align: top;
                            /**/
                            max-width: 90% !important;
                        }
                        .yt-listbox {
                            min-width: 200px !important;
                            max-width: 500px !important;
                            max-height: 500px !important;
                            padding: 10px 10px !important;
                            overflow: auto !important;
                        }
                        #yt-widget.yt-state_bottom .yt-listbox {
                            bottom: unset !important;
                        }
                        .yt-listbox li {
                            display: block !important; 
                        }
                        .yt-servicelink {
                            display: none !important;
                        }
                    </style>
                    
                    
<div id="ytWidget"></div>

<script src="https://translate.yandex.net/website-widget/v1/widget.js?widgetId=ytWidget&pageLang=en&widgetTheme=light&autoMode=true" type="text/javascript"></script>
                    </a>
                   
                   
                   
                    
                                    
                                    
                                    <form method="POST" class="mt-4">
                        
                        
                                         <div class="mb-4 text-white">

                            <h4 class="mb-2">Login to your account</h4>
                            <p>You can sign in to your account using email or username</p>
                        </div>
                        <div class="row">
                            
                            
                            
                            <div class="col-12">
                                <p style="color:sandybrown"></p>
                                <div class="form-group">
                                    <label class="form-label">Email</label>
                                    <input type="email" name="email"
                                                    placeholder="enter email" required class="form-control form--control h-45" value=""
                                          >
                                </div>
                            </div>
                            
                            
                            
                            <div class="col-12">
                                <div class="form-group">
                                    <label class="form-label">Password</label>
                                    <input type="password" name="password" class="form-control form--control h-45"
                                           placeholder="Enter Password">
                                </div>
                            </div>
                            
                            
                            
                            <div class="col-12">
                                <div class="d-flex flex-wrap gap-2 justify-content-between">
                                    <div class="form-group custom--checkbox">
                                        <input type="checkbox" id="remember" name="remember" class="form-check-input" >
                                        <label for="remember">Keep me Logged in</label>
                                    </div>
                                    <a href="forget_password.php" class="text--base fw-bold">
                                        Forgot
                                        Password?
                                    </a>
                                </div>
                            </div>
                            <div class="col-12">
                            </div>
                            <div class="col-12">
                               
                                
                                <button class="btn btn--base w-100" type="submit">Login Account</button>
                                
                            </div>
                            <div class="col-12 mt-4">
                                <p class="text-center text-white">
                                    Don't have any account? <a href="register.php"
                                                               class="fw-bold text--base">Create Account</a>
                                </p>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </section>
    <!-- Account Section -->

<?php require ("footer.php") ?>