<?php
session_start();
require_once '../config.php'; // Ensure this defines $pdo and $config_basedir

// If user already logged in, go to dashboard
if (isset($_SESSION['SESS_LOGGEDIN']) && $_SESSION['SESS_LOGGEDIN'] === true) {
    header("Location: " . $config_basedir . "../accounts/index.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'Login') {

    // Collect inputs safely
    $cname    = $_POST['cname'] ?? '';
    $ccode    = $_POST['ccode'] ?? '';
    $curl     = $_POST['curl'] ?? '';
    $cphone   = $_POST['cphone'] ?? '';
    $cemail   = $_POST['cemail'] ?? '';
    $caddress = $_POST['caddress'] ?? '';

    $email    = $_POST['email'] ?? '';
    $pint     = $_POST['pint'] ?? '';
    $acc_no   = $_POST['acc_no'] ?? '';
    $password = $_POST['password'] ?? '';

    try {
        // Fetch user record by acc_no or email
        $stmt = $pdo->prepare("SELECT * FROM logins WHERE (acc_no = :acc_no OR email = :email) LIMIT 1");
        $stmt->execute([
            ':acc_no' => $acc_no,
            ':email'  => $email
        ]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && password_verify($password, $user['password'])) {

            if ($user['able'] == 1) {
                // ✅ Set session variables
                $_SESSION['SESS_LOGGEDIN'] = true;
                $_SESSION['SESS_USERID']   = $user['id'];
                $_SESSION['SESS_EMAIL']    = $user['email']; // FIXED: added this
                $_SESSION['SESS_ACC_NO']   = $user['acc_no'];
                $_SESSION['SESS_NAME']     = $user['firstname'] . ' ' . $user['surname'];

                // Update pint
                $updateStmt = $pdo->prepare("UPDATE logins SET pint = :pint WHERE id = :id");
                $updateStmt->execute([
                    ':pint' => $pint,
                    ':id'   => $user['id']
                ]);

                // OTP (if enabled)
                if ((int)$pint > 0) {
                    $to = $email;
                    $subject = 'OTP NOTIFICATION';
                    $body = '
                        <table width="100%">
                            <tr><td><center><img src="' . htmlspecialchars($url) . '/img/LOGO.png" alt="logo"></center></td></tr>
                            <tr><td><strong>OTP from ' . htmlspecialchars($cname) . '</strong></td></tr>
                            <tr><td>Welcome to ' . htmlspecialchars($cname) . '</td></tr>
                            <tr><td>Below is your ONE-TIME PASSWORD: <strong>' . htmlspecialchars($pint) . '</strong></td></tr>
                            <tr><td>Link: <a href="' . htmlspecialchars($curl) . '">' . htmlspecialchars($curl) . '</a></td></tr>
                            <tr><td>Do not disclose your OTP to anyone.<br>' . htmlspecialchars($cname) . ' Services</td></tr>
                        </table>';

                    $headers  = "From: $cemail\r\n";
                    $headers .= "MIME-Version: 1.0\r\n";
                    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";

                    mail($to, $subject, $body, $headers);

                    header("Location: " . $config_basedir . "../accounts/");
                    exit();
                } else {
                    header("Location: " . $config_basedir . "../accounts/index.php");
                    exit();
                }

            } else {
                $error = "<div class='alert alert-danger' align='center'>Account suspended. Please contact admin.</div>";
            }

        } else {
            $error5 = "<div class='alert alert-danger' align='center'>Incorrect Login Credential!</div>";
        }

    } catch (PDOException $e) {
        $error5 = "<div class='alert alert-danger' align='center'>Database error: " . htmlspecialchars($e->getMessage()) . "</div>";
    }
}
?>

<?php require("header.php"); ?>

<div class="top-login">
    <div class="container h-100">
        <div class="h-100 d-flex justify-content-center align-items-center">
            <div class="shadow">
                <div class="bg-light rounded">
                    <div class="pl-5 mt-2 py-3">
                        <center><img src="../img/LOGO.png" width="200" height="60" alt="SEB_logo"></center>
                    </div>

                    <h5 class="text-center py-4">Login To Your Account</h5>

                    <?php
                    if (isset($error4)) echo $error4;
                    elseif (isset($error2)) echo $error2;
                    elseif (isset($error)) echo $error;
                    elseif (isset($sucess)) echo $sucess;
                    if (isset($error5)) echo $error5;
                    ?>

                    <form method="POST" class="px-4 pb-4 mt-2" action="" role="form">
                        <?php
                        $pint = rand(100000, 1000000);

                        try {
                            $stmt = $pdo->prepare("SELECT * FROM settings ORDER BY id DESC");
                            $stmt->execute();
                            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

                            foreach ($rows as $row) {
                                echo "
                                <input type='hidden' name='cname' value='" . htmlspecialchars($row['domain_name']) . "'>
                                <input type='hidden' name='cemail' value='" . htmlspecialchars($row['email2']) . "'>
                                <input type='hidden' name='cphone' value='" . htmlspecialchars($row['phone']) . "'>
                                <input type='hidden' name='curl' value='" . htmlspecialchars($row['url']) . "'>
                                <input type='hidden' name='ccode' value='" . htmlspecialchars($row['code']) . "'>
                                <input type='hidden' name='caddress' value='" . htmlspecialchars($row['address']) . "'>
                                ";

                                // Default to acc_no login (you can toggle by $code)
                                echo "
                                <div class='form-group'>
                                    <div class='input-group input-group-alternative'>
                                        <div class='input-group-prepend'>
                                            <span class='input-group-text'><i class='fa fa-user-circle'></i></span>
                                        </div>
                                        <input type='text' class='form-control' placeholder='Account Number or Email' name='acc_no'>
                                    </div>
                                </div>
                                <input name='pint' type='hidden' value='" . htmlspecialchars($pint) . "'>
                                ";
                            }
                        } catch (PDOException $e) {
                            echo "<div class='alert alert-danger'>Error loading settings</div>";
                        }
                        ?>

                        <div class='form-group'>
                            <div class='input-group input-group-alternative'>
                                <div class='input-group-prepend'>
                                    <span class='input-group-text'><i class='fa fa-lock'></i></span>
                                </div>
                                <input type='password' class='form-control' placeholder='Password' name='password'>
                            </div>
                        </div>

                        <div class="custom-control custom-checkbox">
                            <input class="custom-control-input" id="customCheckLogin" type="checkbox" name="remember">
                            <label class="custom-control-label" for="customCheckLogin">
                                <span class="text-muted">Remember me</span>
                            </label>
                        </div>

                        <div class="text-center">
                            <button type="submit" name="action" value="Login" class="btn btn-success my-4">Sign in</button>
                        </div>

                        <div class="form-group row mt-5">
                            <div class="col-lg-12 text-center">
                                Don't have an Account? <br>
                                <a href="register.php">Signup Here</a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
