<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Add error log at the start
    error_log("Login attempt started - " . date('Y-m-d H:i:s'));
    
    try {
        // Include your database connection file
        include 'layouts/dbconn.php';
        
        // Log received data (be careful with passwords in production)
        error_log("Username received: " . $_POST['username']);
        
        // Get username and password from the login form
        $username = $_POST['username'];
        $password = $_POST['password'];
        
        // Validate input
        if (empty($username) || empty($password)) {
            throw new Exception("Username or password cannot be empty");
        }
        
        // Perform a SQL query to check if the user exists
        $sql = "SELECT * FROM users WHERE username = ?";
        $stmt = $conn->prepare($sql);
        
        if (!$stmt) {
            throw new Exception("Database prepare failed: " . $conn->error);
        }
        
        $stmt->bind_param("s", $username);
        
        if (!$stmt->execute()) {
            throw new Exception("Database execute failed: " . $stmt->error);
        }
        
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $user = $result->fetch_assoc();
            error_log("User found in database");
            
            // Verify the password
            if (password_verify($password, $user['password'])) {
                error_log("Password verified successfully");
                
                // Set session variables
                $_SESSION['full_name'] = $user['full_name'];
                $_SESSION['email'] = $user['email'];
                $_SESSION['user_id'] = $user['user_id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['role_id'] = $user['role_id'];
                
                // Return JSON response for AJAX
                header('Content-Type: application/json');
                echo json_encode([
                    'success' => true,
                    'role_id' => $user['role_id'],
                    'message' => 'Login successful'
                ]);
                exit();
            } else {
                throw new Exception("Invalid password");
            }
        } else {
            throw new Exception("User not found");
        }
    } catch (Exception $e) {
        error_log("Login error: " . $e->getMessage());
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'message' => "Login failed: " . $e->getMessage()
        ]);
        exit();
    } finally {
        if (isset($stmt)) {
            $stmt->close();
        }
        if (isset($conn)) {
            $conn->close();
        }
    }
}

// If it's not a POST request but the file is accessed directly
if ($_SERVER["REQUEST_METHOD"] != "POST") {
    error_log("Non-POST request received to login script");
}
?>
<?php include 'layouts/main.php'; ?>

<head>

    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Sign In')); ?>

    <?php include 'layouts/head-css.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
</head>

<body>

    <!-- auth-page wrapper -->
    <div class="auth-page-wrapper py-5 d-flex justify-content-center align-items-center min-vh-100">
        
        <!-- auth-page content -->
        <div class="auth-page-content overflow-hidden pt-lg-5">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card overflow-hidden">
                            <div class="row g-0">
                                <div class="col-lg-6">
                                    <div class="p-lg-5 p-4  h-100">
                                        
                                       <div class="position-relative h-100 d-flex flex-column align-items-center justify-content-center">
                                            <div class="mb-4 mt-8 ms-5">  <!-- added ms-5 for left margin -->
                                                <a href="index.php" class="d-block">
                                                    <img src="assets/images/logo-rf.png" alt="" height="75">
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <!-- end col -->

                                <div class="col-lg-6">
                                    <div class="p-lg-5 p-4">
                                        <div>
                                            <h5 class="text-primary">Welcome Back !</h5>
                                            <p class="text-muted">Sign in to continue to Royal Freight Ltd</p>
                                        </div>

                                        <div class="mt-4">
                                            <!-- Display error message if set -->
                                            <?php if(isset($error_message)): ?>
                                                <div><?php echo $error_message; ?></div>
                                            <?php endif; ?>
                                            <form id="login-form" method="POST">

                                                <div class="mb-3">
                                                    <label for="username" class="form-label">Username</label>
                                                    <input type="text" class="form-control" id="username" name="username" placeholder="Enter username">
                                                </div>

                                                <div class="mb-3">
                                                    <div class="float-end">
                                                        <a href="auth-pass-reset-cover.php" class="text-muted">Forgot password?</a>
                                                    </div>
                                                    <label class="form-label" for="password">Password</label>
                                                    <div class="position-relative auth-pass-inputgroup mb-3">
                                                        <input type="password" class="form-control pe-5 password" placeholder="Enter password" id="password" name="password">
                                                        <button class="btn btn-link position-absolute end-0 top-0 text-decoration-none text-muted password-addon" type="button" id="password-addon"><i class="ri-eye-fill align-middle"></i></button>
                                                    </div>
                                                </div>

                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" value="" id="auth-remember-check">
                                                    <label class="form-check-label" for="auth-remember-check">Remember me</label>
                                                </div>

                                                <div class="mt-4">
                                                    <button class="btn btn-info w-100" type="submit">Sign In</button>
                                                </div>

                                            </form>
                                        </div>

                                        <div class="mt-5 text-center">
                                            <p class="mb-0">Don't have an account ? <a href="#" class="fw-semibold text-primary text-decoration-underline"> Signup</a> </p>
                                        </div>
                                    </div>
                                </div>
                                <!-- end col -->
                            </div>
                            <!-- end row -->
                        </div>
                        <!-- end card -->
                    </div>
                    <!-- end col -->

                </div>
                <!-- end row -->
            </div>
            <!-- end container -->
        </div>
        <!-- end auth page content -->

        <!-- footer -->
        <footer class="footer">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="text-center">
                            <p class="mb-0">&copy;
                                <script>document.write(new Date().getFullYear())</script> Royal Freight Ltd
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </footer>
        <!-- end Footer -->
    </div>
    <!-- end auth-page-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>

    <!-- password-addon init -->
    <script src="assets/js/pages/password-addon.init.js"></script>
<script>
document.getElementById('login-form').addEventListener('submit', function(event) {
    event.preventDefault();
    console.log('Form submitted'); // Debug log

    var formData = new FormData(this);

    // Log form data (except password)
    for (var pair of formData.entries()) {
        if (pair[0] !== 'password') {
            console.log(pair[0] + ': ' + pair[1]);
        }
    }

    fetch('login_process.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        console.log('Response status:', response.status); // Debug log
        return response.json();
    })
    .then(data => {
        console.log('Response data:', data); // Debug log
        
        if (data.success) {
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: 'Login successful',
                showConfirmButton: false,
                timer: 1500
            }).then(() => {
                window.location.href = data.role_id == '1' ? 'index.php' : 'dashboard.php';
            });
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: data.message || 'Login failed'
            });
        }
    })
    .catch(error => {
        console.error('Fetch error:', error); // Debug log
        Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: 'An unexpected error occurred'
        });
    });
});
</script>
</body>

</html>