<?php
// Error reporting (Production mein isko 0 kar dena)
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once file_exists(__DIR__ . '/config.php') ? 'config.php' : 'config/config.php';

// Agar user already logged in hai, toh sidha home page par bhej do
if (isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit;
}

// ==========================================
// BACKEND: AJAX LOGIN VERIFICATION
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'login') {
    header('Content-Type: application/json');
    
    $mobile = trim($_POST['mobile'] ?? '');
    $password = $_POST['password'] ?? '';

    // Validation
    if (empty($mobile) || empty($password)) {
        echo json_encode(['success' => false, 'message' => 'Please enter mobile number and password.']);
        exit;
    }
    if (strlen($mobile) < 10) {
        echo json_encode(['success' => false, 'message' => 'Invalid mobile number format.']);
        exit;
    }

    try {
        global $pdo;
        // Check user in database
        $stmt = $pdo->prepare("SELECT id, password, status FROM users WHERE mobile = ?");
        $stmt->execute([$mobile]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        // Verify Password
        if ($user && password_verify($password, $user['password'])) {
            // Check if account is blocked
            if ($user['status'] === 'blocked') {
                echo json_encode(['success' => false, 'message' => 'Your account is blocked. Contact support.']);
                exit;
            }
            
            // Login Success -> Set Session
            $_SESSION['user_id'] = $user['id'];
            echo json_encode(['success' => true, 'message' => 'Login Successful! Redirecting...']);
            exit;
        } else {
            echo json_encode(['success' => false, 'message' => 'Incorrect mobile number or password.']);
            exit;
        }
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Server error. Please try again.']);
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Login - <?= defined('APP_NAME') ? APP_NAME : '91CLUB' ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { 
            --primary: #eb4d4b; 
            --primary-gradient: linear-gradient(90deg, #ff7675, #eb4d4b);
            --bg: #ffffff; 
            --text-dark: #2f3640; 
            --text-muted: #7f8fa6; 
            --border-color: #dcdde1;
        }
        
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Inter', sans-serif; -webkit-tap-highlight-color: transparent; }
        
        body { 
            background: #f5f6fa; /* Light grey body behind the mobile frame */
            color: var(--text-dark); 
            min-height: 100vh;
        }

        /* Mobile Frame Wrapper */
        .app-container {
            max-width: 480px;
            margin: 0 auto;
            background: var(--bg);
            min-height: 100vh;
            box-shadow: 0 0 20px rgba(0,0,0,0.05);
            position: relative;
        }

        /* Header Style */
        .auth-header { 
            display: flex; 
            align-items: center; 
            padding: 16px 20px;
            background: var(--bg);
            position: sticky;
            top: 0;
            z-index: 10;
        }
        .back-btn { font-size: 20px; color: var(--text-dark); text-decoration: none; }
        .auth-title { flex: 1; text-align: center; font-size: 18px; font-weight: 700; padding-right: 20px; color: var(--text-dark); }
        
        .auth-body { padding: 20px 24px; }
        
        /* Logo Area */
        .logo-area { text-align: center; margin-bottom: 30px; margin-top: 10px; }
        .logo-area .icon-wrap { width: 65px; height: 65px; margin: 0 auto 12px; background: var(--bg); border-radius: 16px; display: flex; align-items: center; justify-content: center; box-shadow: 0 8px 20px rgba(235, 77, 75, 0.2); }
        .logo-area .icon-wrap i { font-size: 32px; color: var(--primary); }
        .logo-area h1 { font-size: 24px; font-weight: 800; color: var(--primary); letter-spacing: -0.5px; }

        /* Tabs (Password Login / OTP Login) */
        .auth-tabs { 
            display: flex; 
            border-bottom: 2px solid #f1f2f6; 
            margin-bottom: 30px; 
        }
        .tab-btn { 
            flex: 1; 
            text-align: center; 
            padding: 12px 0; 
            font-size: 15px;
            font-weight: 600; 
            color: var(--text-muted); 
            cursor: pointer; 
            transition: 0.3s;
        }
        .tab-btn.active { 
            color: var(--primary); 
            border-bottom: 3px solid var(--primary); 
            margin-bottom: -2px; 
        }

        /* Input Fields */
        .input-group { 
            display: flex; 
            align-items: center; 
            border-bottom: 1px solid var(--border-color); 
            padding: 10px 0; 
            margin-bottom: 24px; 
            transition: 0.3s;
        }
        .input-group:focus-within { border-bottom-color: var(--primary); }
        .input-group i.icon-left { color: var(--primary); font-size: 20px; width: 30px; text-align: left; }
        .country-code { font-weight: 600; color: var(--text-dark); margin-right: 12px; font-size: 15px; }
        .form-control { 
            flex: 1; 
            padding: 8px 0; 
            border: none; 
            background: transparent; 
            outline: none; 
            font-size: 15px; 
            color: var(--text-dark); 
            font-weight: 500; 
        }
        .form-control::placeholder { color: #b2bec3; font-weight: 400; }
        .eye-icon { color: var(--text-muted); cursor: pointer; padding-left: 10px; font-size: 18px; }

        /* Utils (Remember / Forgot Password) */
        .auth-utils { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; }
        .remember-me { display: flex; align-items: center; gap: 8px; font-size: 14px; color: var(--text-muted); font-weight: 500; }
        .remember-me input { width: 18px; height: 18px; accent-color: var(--primary); }
        .forgot-pass { color: var(--primary); font-size: 14px; font-weight: 600; text-decoration: none; }

        /* Buttons */
        .submit-btn { 
            width: 100%; 
            background: var(--primary-gradient); 
            color: #fff; 
            border: none; 
            padding: 16px; 
            border-radius: 30px; 
            font-size: 16px; 
            font-weight: 700; 
            cursor: pointer; 
            box-shadow: 0 6px 15px rgba(235, 77, 75, 0.3); 
            transition: 0.2s; 
            margin-bottom: 16px;
        }
        .submit-btn:active { transform: scale(0.98); box-shadow: 0 2px 10px rgba(235, 77, 75, 0.2); }
        .submit-btn:disabled { opacity: 0.7; cursor: not-allowed; }
        
        .register-btn { 
            width: 100%; 
            background: transparent; 
            color: var(--primary); 
            border: 1px solid var(--primary); 
            padding: 15px; 
            border-radius: 30px; 
            font-size: 16px; 
            font-weight: 700; 
            cursor: pointer; 
            display: block;
            text-align: center;
            text-decoration: none;
            transition: 0.2s; 
        }
        .register-btn:active { background: rgba(235, 77, 75, 0.05); }

        /* Customer Support Link */
        .support-link { text-align: center; margin-top: 30px; display: block; }
        .support-link a { color: var(--text-muted); font-size: 14px; text-decoration: none; font-weight: 500; display: flex; align-items: center; justify-content: center; gap: 6px; }

        /* Toast Message (Dark on white bg for visibility) */
        .toast { position: fixed; bottom: 30px; left: 50%; transform: translateX(-50%) translateY(100px); background: #2f3640; color: #fff; padding: 14px 24px; border-radius: 30px; font-size: 14px; font-weight: 500; box-shadow: 0 10px 30px rgba(0,0,0,0.2); z-index: 9999; display: flex; align-items: center; gap: 10px; opacity: 0; transition: all 0.35s ease; white-space: nowrap; }
        .toast.show { transform: translateX(-50%) translateY(0); opacity: 1; }
        .toast.success i { color: #2ecc71; }
        .toast.error i { color: #ff4757; }
    </style>
</head>
<body>

<div class="app-container">
    
    <div id="toastBox" class="toast">
        <i class="fas fa-info-circle"></i>
        <span id="toastMsg">Message here</span>
    </div>

    <div class="auth-header">
        <a href="index.php" class="back-btn"><i class="fas fa-angle-left"></i></a>
        <div class="auth-title">Log in</div>
    </div>

    <div class="auth-body">
        
        <div class="logo-area">
            <div class="icon-wrap">
                <i class="fas fa-crown"></i>
            </div>
            <h1><?= defined('APP_NAME') ? APP_NAME : '91CLUB' ?></h1>
        </div>

        <div class="auth-tabs">
            <div class="tab-btn active"><i class="fas fa-key me-1"></i> Password</div>
            <div class="tab-btn" onclick="showToast('OTP Login coming soon!', 'error')"><i class="fas fa-mobile-alt me-1"></i> SMS code</div>
        </div>

        <form id="loginForm" onsubmit="executeLogin(event)">
            
            <div class="input-group">
                <i class="fas fa-mobile-alt icon-left"></i>
                <div class="country-code">+91</div>
                <input type="tel" name="mobile" class="form-control" placeholder="Phone number" required maxlength="10" pattern="[0-9]{10}" autocomplete="off">
            </div>

            <div class="input-group">
                <i class="fas fa-lock icon-left"></i>
                <input type="password" name="password" id="passwordInput" class="form-control" placeholder="Password" required autocomplete="off">
                <i class="fas fa-eye-slash eye-icon" id="eyeIcon" onclick="togglePassword()"></i>
            </div>

            <div class="auth-utils">
                <label class="remember-me">
                    <input type="checkbox" checked> Remember password
                </label>
            </div>

            <button type="submit" class="submit-btn" id="loginBtn">Log in</button>
            <a href="register.php" class="register-btn">Register</a>
        </form>

        <div class="support-link">
            <a href="#"><i class="fas fa-headset"></i> Customer Service</a>
        </div>

    </div>
</div>

<script>
    // Toggle Password Visibility
    function togglePassword() {
        const passInput = document.getElementById('passwordInput');
        const eyeIcon = document.getElementById('eyeIcon');
        
        if (passInput.type === 'password') {
            passInput.type = 'text';
            eyeIcon.classList.remove('fa-eye-slash');
            eyeIcon.classList.add('fa-eye');
            eyeIcon.style.color = 'var(--primary)';
        } else {
            passInput.type = 'password';
            eyeIcon.classList.remove('fa-eye');
            eyeIcon.classList.add('fa-eye-slash');
            eyeIcon.style.color = 'var(--text-muted)';
        }
    }

    // Custom Toast Notification System
    function showToast(message, type = 'success') {
        const toast = document.getElementById('toastBox');
        const msgSpan = document.getElementById('toastMsg');
        const icon = toast.querySelector('i');
        
        msgSpan.innerText = message;
        toast.className = 'toast show ' + type;
        
        if(type === 'success') {
            icon.className = 'fas fa-check-circle';
        } else {
            icon.className = 'fas fa-times-circle';
        }

        // Hide after 3 seconds
        setTimeout(() => {
            toast.classList.remove('show');
        }, 3000);
    }

    // AJAX Login Execution
    function executeLogin(e) {
        e.preventDefault(); // Stop page reload
        
        const btn = document.getElementById('loginBtn');
        const form = document.getElementById('loginForm');
        const formData = new FormData(form);
        formData.append('action', 'login'); // Tells PHP to execute login block

        // Button Loading State
        const originalBtnText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Logging in...';
        btn.disabled = true;

        // API Call to same page
        fetch('login.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast(data.message, 'success');
                // Smooth Redirect to Home Page
                setTimeout(() => {
                    window.location.href = 'index.php';
                }, 1200);
            } else {
                showToast(data.message, 'error');
                btn.innerHTML = originalBtnText;
                btn.disabled = false;
            }
        })
        .catch(error => {
            showToast('Network error! Please try again.', 'error');
            btn.innerHTML = originalBtnText;
            btn.disabled = false;
        });
    }
</script>
</body>
</html>