<?php
session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require 'phpmailer/phpmailer/src/PHPMailer.php';
require 'phpmailer/phpmailer/src/Exception.php';
require 'phpmailer/phpmailer/src/SMTP.php';

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

require 'db_connection.php'; // Your database connection file

$error_message = ''; // Initialize error message
$success_message = ''; // Initialize success message

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $phone = isset($_POST["phone"]) ? mysqli_real_escape_string($conn, $_POST["phone"]) : (isset($_COOKIE["phone"]) ? $_COOKIE["phone"] : '');
    $password = $_POST['password'];
    $login_status = "Failed"; // Default to failed login

    // Check if the phone number exists using prepared statement to prevent SQL injection
    $sql_check = "SELECT * FROM customer WHERE phone = ?";
    $stmt = $conn->prepare($sql_check);
    $stmt->bind_param("s", $phone);
    $stmt->execute();
    $result_check = $stmt->get_result();

    if ($result_check->num_rows > 0) {
        // Phone exists, fetch user data
        $row = $result_check->fetch_assoc();

        // Check if the user is verified
        if ($row['verified'] == 0) {
            $_SESSION['verification_code'] = $verificationCode;
            $_SESSION['registered_mobile'] = $phone;
            $_SESSION['verified'] = false;

            // Redirect to verification page if not verified
            header("Location: verification.php");
            exit;
        }

        // Verify password using password_hash and password_verify
        if (password_verify($password, $row['password'])) {
            // Set session variables for successful login
            $_SESSION['user_id'] = $row['id'];
            $_SESSION['fullname'] = $row['fullname'];
            $_SESSION['email'] = $row['email'];
            $_SESSION['registered_mobile'] = true;
            $_SESSION['verified'] = true;
            $_SESSION['phone'] = $row['phone'];

            // Set cookies for 2 years (2 * 365 days)
            $two_years = time() + (2 * 365 * 24 * 60 * 60);
            setcookie("phone", $row['phone'], $two_years, "/", "", false, true); // HttpOnly flag set
            setcookie("fullname", $row['fullname'], $two_years, "/", "", false, true);

            $login_status = "Successful";
            $success_message = "Login successful! Redirecting to your dashboard...";

            // Redirect to dashboard after 3 seconds
            header("refresh:3;url=home.php");
            exit;
        } else {
            $error_message = "Invalid phone number or password.";
        }
    } else {
        $error_message = "Invalid phone number or password.";
    }
}

// Handle "Switch User" action
if (isset($_GET['action']) && $_GET['action'] === 'switch_user') {
    // Destroy cookies for the current user
    setcookie("phone", "", time() - 3600, "/");
    setcookie("fullname", "", time() - 3600, "/");

    // Destroy the session and redirect back to the login page
    session_destroy();
    header("Location: login.php");
    exit;
}

// Close the prepared statement and the database connection
if (isset($stmt)) {
    $stmt->close();
}
$conn->close();
?>

<!DOCTYPE html>
<html lang="zxx">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Twins Apple</title>
    <meta name="Googlebot" content="noindex">
    <meta name="description" content="Carce is an exclusive ecommerce mobile app template with 2 distinct layouts. This superb mobile app template for ecommerce embodies a professional-looking mobile website design while providing tons of features.">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- ::::::::::::::Favicon icon::::::::::::::-->
    <link rel="shortcut icon" href="assets/images/favicon.ico" type="image/png">

    <!-- ::::::::::::::All Google Fonts::::::::::::::-->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="">
    <link href="../../css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">

    <!-- ::::::::::::::All CSS Files here :::::::::::::: -->
    <!-- Vendor CSS -->
    <link rel="stylesheet" href="assets/css/vendor/icomoon.css">

    <!-- Plugin CSS -->
    <link rel="stylesheet" href="assets/css/plugins/swiper-bundle.min.css">
    <link rel="stylesheet" href="assets/css/plugins/ion.rangeSlider.min.css">

    <!-- Style CSS -->
    <link rel="stylesheet" href="assets/css/style.css">

</head>

<body>

    <main class="main-wrapper">
        <!-- ...:::Start Login Section:::... -->
        <div class="login-section">
            <div class="container">
                <!-- Start User Event Area -->
                <div class="login-wrapper">
                    <div class="section-content">
                        <h1 class="title">Welcome Back</h1>
                        <p>Login with your account to continue.</p>
                    </div>

                    <!-- Display Error Message -->
                   

                    <form action="" method="POST" class="default-form-wrapper">
                        <ul class="default-form-list">
                            <li class="single-form-item">
                                <label for="name" class="visually-hidden">Phone No.</label>
                                <input type="text" id="phone" name="phone" placeholder="phone" required>
                                <span class="icon"><i class="icon icon-carce-user"></i></span>
                            </li>
                            <li class="single-form-item">
                                <label for="password" class="visually-hidden">Password</label>
                                <input type="password" id="password" name="password" placeholder="password" required>
                                <span class="icon"><i class="icon icon-carce-eye"></i></span>
                            </li>
                        </ul>


 <?php if (!empty($error_message)): ?>
                        <div class="error-message" style="color: red; font-weight: bold;">
                            <?php echo $error_message; ?>
                        </div>
                    <?php endif; ?>

                        <br><br>

                        <div class="page-progress-wrapper">
                            <button type="submit" class="btn--center btn--round btn--size-58-58 btn--color-white btn--radical-red progress-btn progress-btn--50">
                                <i class="icon icon-carce-ios-arrow-forward"></i>
                            </button>
                        </div>

                    </form>
                    <a href="forgot.php" class="forgot-link">Forgot Password?</a>
                </div>

                <div class="create-account-text text-center">Don't have an account? <a href="register.php" class="btn--color-radical-red">Create now</a></div>
                <!-- End User Event Area -->

            </div>
        </div>
        <!-- ...:::End User Event Section:::... -->

    </main>

    <!-- ::::::::::::::All JS Files here :::::::::::::: -->
    <script src="assets/js/vendor/modernizr-3.11.2.min.js"></script>
    <script src="assets/js/vendor/jquery-3.6.0.min.js"></script>
    <script src="assets/js/vendor/jquery-migrate-3.3.2.min.js"></script>
    <script src="assets/js/plugins/swiper-bundle.min.js"></script>
    <script src="assets/js/plugins/ion.rangeSlider.min.js"></script>
    <script src="assets/js/main.js"></script>

</body>

</html>
