<?php
session_start();
include('./includes/config.php');
include('./template/ahkweb/authentication-signin.php');

if (isset($_POST['username']) && !empty($_POST['username'])) {
    $username = mysqli_real_escape_string($ahk_conn, $_POST['username']);
    $password = mysqli_real_escape_string($ahk_conn, $_POST['password']);

    $fetch = mysqli_query($ahk_conn, "SELECT * FROM users WHERE phone='$username' OR email='$username'");

    if ($fetch && mysqli_num_rows($fetch) === 1) {
        $userData = mysqli_fetch_assoc($fetch);

        // First check if account is active
        if ($userData['status'] == 1) {
            // Then check password
            if (password_verify($password, $userData['password'])) {

                // Set session variables
                $_SESSION['phone'] = $userData['phone'];
                $_SESSION['name'] = $userData['name'];

                $user = $userData['name'];
                $login_time = date('Y-m-d H:i:s');
                $login_ip = $_SERVER['REMOTE_ADDR'];
                $site = "$websiteUrl/login";

                $message =
            "🔐 Login Alert – {$webname}\n\n" .
            "Dear {$user},\n\n" .
            "You have successfully logged in.\n\n" .
            "🕒 Time: {$login_time}\n" .
            "🌐 IP: {$login_ip}\n\n" .
            "If this was NOT you, please change your password immediately.\n\n" .
            "Login URL: {$site}\n\n" .
            "— Security Team";

        $msg = urlencode($message);

        $api_url = "https://{$whatsappurl}/send-message"
                 . "?api_key={$whapikey}"
                 . "&sender={$whsender}"
                 . "&number=91{$userData['phone']}"
                 . "&message={$msg}";

        // ✅ Send WhatsApp via cURL
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $api_url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 15,
            CURLOPT_SSL_VERIFYPEER => false
        ]);
        curl_exec($ch);
        curl_close($ch);
                ?>

                <script>
                    $(function () {
                        Swal.fire({
                            title: "✅ Login Successful",
                            text: "<?php echo ahkweb('webname'); ?> - Welcome back!",
                            icon: "success",
                            timer: 2000,
                            showConfirmButton: false,
                            timerProgressBar: true
                        });

                        setTimeout(() => {
                            window.location.href = 'admin';
                        }, 1800);

                        fetch("<?php echo $whatsapp_url; ?>");
                    });
                </script>

                <?php
            } else {
                // Incorrect password
                ?>
                <script>
                    $(function () {
                        Swal.fire({
                            title: "❌ Incorrect Password",
                            text: "The password you entered is incorrect.",
                            icon: "error",
                            confirmButtonColor: "#d33"
                        });
                    });
                </script>
                <?php
            }
        } else {
            // Account not active
            ?>
            <script>
                $(function () {
                    Swal.fire({
                        title: "🚫 Account Inactive",
                        text: "Your account is not active. Please contact support.",
                        icon: "warning",
                        confirmButtonColor: "#f39c12"
                    });
                });
            </script>
            <?php
        }
    } else {
        // No such user
        ?>
        <script>
            $(function () {
                Swal.fire({
                    title: "📛 Not Registered",
                    text: "The email or phone number is not registered.",
                    icon: "error",
                    confirmButtonColor: "#d33"
                });
            });
        </script>
        <?php
    }
}
?>
