<!-- login.php -->
<?php
// Set session timeout (must be done before session_start)
ini_set('session.gc_maxlifetime', 1800); // 30 minutes

// Set secure session cookie parameters (in production)
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
    ini_set('session.cookie_secure', 1);
    ini_set('session.cookie_httponly', 1);
}

// Configure session cookie parameters
session_set_cookie_params(1800); // 30 minutes lifetime

// Start session
session_start();

// Enable error logging for debugging
error_log("Session started with ID: " . session_id());

// Include database connection
require_once "config/connection.php";

// Initialize variables
$loginError = "";
$success = false;

// Define a function to handle redirection
function redirectToDashboard($user_type, $user_id) {
    // Base path detection
    $isSecure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443;
    $protocol = $isSecure ? 'https://' : 'http://';
    $host = $_SERVER['HTTP_HOST'];
    $appRoot = dirname($_SERVER['PHP_SELF']);
    
    // Ensure appRoot has trailing slash if not empty
    if ($appRoot != '/' && $appRoot != '\\') {
        $appRoot = rtrim($appRoot, '/') . '/';
    } else {
        $appRoot = '/';
    }
    
    // Set dashboard paths based on user type
    switch ($user_type) {
        case 'admin':
            $dashboardPath = 'admin/dashboard_admin.php';
            break;
        case 'it':
            $dashboardPath = 'it/dashboard_it.php';
            break;
        case 'borrower':
            $dashboardPath = 'peminjam/dashboard_peminjam.php';
            break;
        default:
            $dashboardPath = 'index.php';
    }
    
    // Construct full URL
    $redirectUrl = $protocol . $host . $appRoot . $dashboardPath;
    
    // Debug
    error_log("Redirecting {$user_type} (ID: {$user_id}) to: {$redirectUrl}");
    
    // Perform redirection with fallbacks
    if (headers_sent($file, $line)) {
        error_log("Headers already sent in $file on line $line");
        echo "<script>window.location.href='" . $redirectUrl . "';</script>";
        echo "<noscript><meta http-equiv='refresh' content='0;url=" . $redirectUrl . "'></noscript>";
        echo "If you are not redirected, <a href='" . $redirectUrl . "'>click here</a>.";
        exit;
    } else {
        header("Location: " . $redirectUrl);
        exit();
    }
}

// Process login
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Debug: Log that a POST request was received
    error_log("POST login request received");
    
    // Get user inputs
    $username = sanitize_input($conn, $_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    
    if (empty($username) || empty($password)) {
        $loginError = "Username dan password tidak boleh kosong";
    } else {
        // Debug: Log login attempt
        error_log("Login attempt for username: " . $username);
        
        // First check in admin_users table
        $stmt = $conn->prepare("SELECT id, username, email, password, status FROM admin_users WHERE username = ?");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows == 1) {
            // Admin found
            $row = $result->fetch_assoc();
            
            // Debug: Log admin found
            error_log("Admin found: " . $row['username']);
            
            // Check if account is active
            if (isset($row['status']) && $row['status'] == 'nonactive') {
                $loginError = "Akun anda sedang nonaktif. Silahkan hubungi IT Support";
                error_log("Inactive admin account: " . $username);
            } 
            // Verify password using our custom function
            else if (verify_password($password, $row['password'])) {
                // Set session variables
                $_SESSION['user_id'] = $row['id'];
                $_SESSION['username'] = $row['username'];
                $_SESSION['email'] = $row['email'];
                $_SESSION['user_type'] = 'admin';
                $_SESSION['logged_in'] = true;
                $_SESSION['lokasi'] = 'Color Room'; // Admins are always in Color Room
                
                // Debug: Log successful login and session data
                error_log("Admin login successful. Session variables set.");
                error_log("User ID: " . $_SESSION['user_id']);
                error_log("User type: " . $_SESSION['user_type']);
                
                // Redirect to dashboard
                redirectToDashboard('admin', $row['id']);
            } else {
                $loginError = "Username atau password tidak valid";
                error_log("Invalid password for admin: " . $username);
            }
        } else {
            // Check in it_users table
            $stmt = $conn->prepare("SELECT id, username, email, password FROM it_users WHERE username = ?");
            $stmt->bind_param("s", $username);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows == 1) {
                // IT user found
                $row = $result->fetch_assoc();
                error_log("IT user found: " . $row['username']);
                
                // Verify password using our custom function
                if (verify_password($password, $row['password'])) {
                    // Set session variables
                    $_SESSION['user_id'] = $row['id'];
                    $_SESSION['username'] = $row['username'];
                    $_SESSION['email'] = $row['email'];
                    $_SESSION['user_type'] = 'it';
                    $_SESSION['logged_in'] = true;
                    $_SESSION['lokasi'] = 'IT Department'; // IT users are in IT Department
                    
                    error_log("IT user login successful");
                    
                    // Redirect to dashboard
                    redirectToDashboard('it', $row['id']);
                } else {
                    $loginError = "Username atau password tidak valid";
                    error_log("Invalid password for IT user: " . $username);
                }
            } else {
                // Check in borrower_users table
                $stmt = $conn->prepare("SELECT id, username, email, password, lokasi_posisi, status FROM borrower_users WHERE username = ?");
                $stmt->bind_param("s", $username);
                $stmt->execute();
                $result = $stmt->get_result();
                
                if ($result->num_rows == 1) {
                    // Borrower found
                    $row = $result->fetch_assoc();
                    error_log("Borrower found: " . $row['username']);
                    
                    // Check if account is active
                    if (isset($row['status']) && $row['status'] == 'nonactive') {
                        $loginError = "Akun anda sedang nonaktif. Silahkan hubungi IT Support";
                        error_log("Inactive borrower account: " . $username);
                    }
                    // Verify password using our custom function
                    else if (verify_password($password, $row['password'])) {
                        // Set session variables
                        $_SESSION['user_id'] = $row['id'];
                        $_SESSION['username'] = $row['username'];
                        $_SESSION['email'] = $row['email'];
                        $_SESSION['user_type'] = 'borrower';
                        $_SESSION['lokasi'] = $row['lokasi_posisi']; // Either 'Painting 1' or 'Painting 2'
                        $_SESSION['logged_in'] = true;
                        
                        error_log("Borrower login successful");
                        
                        // Redirect to dashboard
                        redirectToDashboard('borrower', $row['id']);
                    } else {
                        $loginError = "Username atau password tidak valid";
                        error_log("Invalid password for borrower: " . $username);
                    }
                } else {
                    $loginError = "Username atau password tidak valid";
                    error_log("Username not found: " . $username);
                }
            }
        }
        
        $stmt->close();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Color Access System | Login</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        'poppins': ['Poppins', 'sans-serif'],
                    },
                    backgroundImage: {
                        'gradient-primary': 'linear-gradient(135deg, #2C5364 0%, #203A43 50%, #0F2027 100%)',
                        'gradient-side': 'linear-gradient(225deg, #2C5364 0%, #203A43 50%, #0F2027 100%)',
                        'gradient-button': 'linear-gradient(to right, #2C5364, #203A43, #0F2027)',
                        'gradient-button-hover': 'linear-gradient(to right, #2C5364, #203A43)',
                    },
                    colors: {
                        primary: '#203A43',
                        secondary: '#2C5364',
                        tertiary: '#0F2027',
                    }
                }
            }
        }
    </script>
    <style>
        /* Custom floating label styling */
        .input-group input:focus ~ label,
        .input-group input:not(:placeholder-shown) ~ label {
            top: -1.5rem;
            font-size: 0.75rem;
            color: #2C5364;
        }
        
        .input-group input:focus ~ .underline {
            transform: scaleX(1);
        }
    </style>
</head>
<body class="font-poppins min-h-screen flex items-center justify-center bg-gradient-primary p-5 md:p-10">
    <div class="relative w-full max-w-5xl h-auto md:h-[500px] bg-white/95 shadow-lg overflow-hidden rounded-2xl flex flex-col md:flex-row">
        <!-- Image Section -->
<div class="relative w-full md:w-2/5 bg-gradient-side flex flex-col items-center justify-center p-8 text-white text-center h-[200px] md:h-full">
    <div class="relative rounded-full p-1 bg-white shadow-lg" style="box-shadow: 0 0 20px 5px rgba(255, 255, 255, 0.6);">
        <div class="rounded-full border-4 border-white overflow-hidden" style="filter: drop-shadow(0 0 10px rgba(255, 255, 255, 0.5));">
            <img src="images/logo.png" alt="Logo" class="w-24 h-24 md:w-36 md:h-36 object-contain" id="logoImage">
        </div>
    </div>
    <h2 class="text-2xl font-semibold mb-2 mt-4 md:mt-5">Color Access System</h2>
    <p class="text-sm opacity-90">Sistem peminjaman warna untuk furniture</p>
</div>
        
        <!-- Form Section -->
        <div class="relative w-full md:w-3/5 p-8 md:p-10 flex flex-col justify-center">
            <div class="w-full transition-transform duration-500 ease-in-out">
                <!-- Login Form -->
                <div class="login-form">
                    <h2 class="text-2xl font-semibold mb-8 text-gray-800">Login</h2>
                    
                    <?php if (!empty($loginError)): ?>
                    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
                        <span class="block sm:inline"><?php echo htmlspecialchars($loginError); ?></span>
                    </div>
                    <?php endif; ?>
                    
                    <form id="loginForm" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
                        <div class="input-group relative mb-6">
                            <input type="text" name="username" required class="w-full py-3 text-base text-gray-700 border-b border-gray-300 outline-none bg-transparent transition-all duration-300" placeholder=" " autocomplete="username">
                            <div class="underline absolute bottom-0 left-0 w-full h-0.5 bg-gradient-button scale-x-0 transition-transform duration-300"></div>
                            <label class="absolute top-3 left-0 text-base text-gray-500 pointer-events-none transition-all duration-300">Username</label>
                        </div>
                        <div class="input-group relative mb-6">
                            <input type="password" name="password" required class="w-full py-3 text-base text-gray-700 border-b border-gray-300 outline-none bg-transparent transition-all duration-300" placeholder=" " autocomplete="current-password">
                            <div class="underline absolute bottom-0 left-0 w-full h-0.5 bg-gradient-button scale-x-0 transition-transform duration-300"></div>
                            <label class="absolute top-3 left-0 text-base text-gray-500 pointer-events-none transition-all duration-300">Password</label>
                        </div>
                        <div class="flex justify-between mb-6 text-sm">
                            <label class="flex items-center text-gray-600">
                                <input type="checkbox" name="remember" class="mr-1.5">
                                Remember me
                            </label>
                        </div>
                        <button type="submit" class="w-full h-12 rounded-full text-base text-white font-medium cursor-pointer bg-gradient-button shadow-md hover:bg-gradient-button-hover hover:-translate-y-0.5 transition-all duration-300">Login</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Try to load the logo image
            const logoImage = document.getElementById('logoImage');
            const testImage = new Image();
            testImage.onload = function() {
                logoImage.src = 'images/logo.png';
            };
            testImage.onerror = function() {
                // Keep the placeholder if Logo.png doesn't exist
                console.log('images/logo.png not found, using placeholder');
            };
            testImage.src = 'images/logo.png';
            
            // Add client-side validation (optional additional security)
            const loginForm = document.getElementById('loginForm');
            loginForm.addEventListener('submit', function(event) {
                const username = this.querySelector('input[name="username"]').value.trim();
                const password = this.querySelector('input[name="password"]').value;
                
                if (!username || !password) {
                    event.preventDefault();
                    alert('Username dan password tidak boleh kosong');
                }
            });
        });
    </script>
</body>
</html>