<?php 
date_default_timezone_set('Asia/Kolkata');
$current_time = date('M d, Y, g:i:s A', time());
include('includes/config.php');

// Process login FIRST before any output
$login_error = '';

if(isset($_POST['secret']) && $_POST['secret'] == "ahkwebsolutions" && !empty($_POST['username']) && !empty($_POST['password'])){
    $username = mysqli_real_escape_string($conn,$_POST['username']);
    $password = mysqli_real_escape_string($conn,$_POST['password']);

    $res = mysqli_query($conn,"SELECT * FROM `usertable` WHERE phone='$username' OR emailid='$username' OR userid='$username' ");

    if(mysqli_num_rows($res) == 1 ){
        $userdata = mysqli_fetch_assoc($res);
        $vpass = password_verify($password,$userdata['password']);
        if($vpass){
            if($userdata['status'] == "verified"){
                // Set session variables
                $_SESSION['loggedin'] = true;
                $_SESSION['userid'] = $userdata['userid'];
                $_SESSION['name'] = $userdata['name'];
                $_SESSION['emailid'] = $userdata['emailid'];
                $_SESSION['phone'] = $userdata['phone'];
                $_SESSION['walletamount'] = $userdata['walletamount'];
                $_SESSION['usertype'] = $userdata['usertype'];
                
                // Save session and redirect immediately
                session_write_close();
                header("Location: crs/index.php");
                exit();
            } else {
                $login_error = 'blocked';
            }
        } else {
            $login_error = 'password';
        }
    } else {
        $login_error = 'username';
    }
}

// Already logged in? Redirect to dashboard
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true){
    header("Location: crs/index.php");
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Login | Civil Registration System</title>
    
    <!-- Favicon -->
    <link rel="icon" type="image/png" href="https://dc.crsorgi.gov.in/favicon.png">
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Google Font -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            min-height: 100vh;
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 50%, #1e3c72 100%);
            display: flex;
            flex-direction: column;
        }
        
        /* Header */
        .header {
            background: white;
            padding: 12px 20px;
            box-shadow: 0 2px 15px rgba(0,0,0,0.1);
        }
        
        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .logo-section {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .logo-section img {
            height: 45px;
        }
        
        .logo-text {
            font-size: 14px;
            color: #333;
            font-weight: 600;
        }
        
        /* Main Content */
        .main-content {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 30px 15px;
        }
        
        .login-card {
            background: white;
            border-radius: 16px;
            box-shadow: 0 20px 50px rgba(0,0,0,0.3);
            width: 100%;
            max-width: 420px;
            overflow: hidden;
        }
        
        .card-header-custom {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 30px;
            text-align: center;
            color: white;
        }
        
        .card-header-custom img {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            background: white;
            padding: 8px;
            margin-bottom: 15px;
        }
        
        .card-header-custom h1 {
            font-size: 22px;
            font-weight: 700;
            margin-bottom: 5px;
        }
        
        .card-header-custom p {
            opacity: 0.9;
            font-size: 14px;
            margin: 0;
        }
        
        .card-body-custom {
            padding: 30px;
        }
        
        .form-label {
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
            font-size: 14px;
        }
        
        .input-wrapper {
            position: relative;
            margin-bottom: 20px;
        }
        
        .input-icon {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #999;
            z-index: 5;
        }
        
        .form-control {
            width: 100%;
            padding: 14px 14px 14px 45px;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-size: 15px;
            transition: all 0.3s ease;
        }
        
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.15);
            outline: none;
        }
        
        .form-control::placeholder {
            color: #aaa;
        }
        
        .btn-login {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 10px;
            color: white;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }
        
        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
        }
        
        .btn-login:active {
            transform: translateY(0);
        }
        
        .divider {
            display: flex;
            align-items: center;
            margin: 25px 0;
            color: #999;
            font-size: 13px;
        }
        
        .divider::before,
        .divider::after {
            content: '';
            flex: 1;
            height: 1px;
            background: #e0e0e0;
        }
        
        .divider span {
            padding: 0 15px;
        }
        
        .links-section {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 10px;
        }
        
        .link-btn {
            flex: 1;
            min-width: 140px;
            padding: 12px 15px;
            border-radius: 8px;
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
            text-align: center;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        
        .link-register {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            color: white;
        }
        
        .link-register:hover {
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(17, 153, 142, 0.4);
        }
        
        .link-forgot {
            background: #f5f5f5;
            color: #666;
            border: 1px solid #e0e0e0;
        }
        
        .link-forgot:hover {
            background: #eee;
            color: #333;
        }
        
        /* Footer */
        .footer {
            background: rgba(0,0,0,0.3);
            color: white;
            text-align: center;
            padding: 15px;
            font-size: 13px;
        }
        
        /* Loading Overlay */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255,255,255,0.95);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 9999;
        }
        
        .spinner {
            width: 50px;
            height: 50px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* Responsive */
        @media (max-width: 480px) {
            .header { padding: 10px 15px; }
            .logo-section img { height: 35px; }
            .card-header-custom { padding: 25px 20px; }
            .card-header-custom h1 { font-size: 18px; }
            .card-body-custom { padding: 25px 20px; }
            .links-section { flex-direction: column; }
            .link-btn { min-width: 100%; }
        }
    </style>
</head>
<body>
    <!-- Header -->
    <header class="header">
        <div class="header-content">
            <div class="logo-section">
                <img src="https://dc.crsorgi.gov.in/assets/logo/crs-logo-light.png" alt="CRS Logo">
                <span class="logo-text d-none d-sm-inline">Civil Registration System</span>
            </div>
            <div class="logo-section">
                <img src="https://dc.crsorgi.gov.in/assets/images/emblem.png" alt="Emblem">
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <main class="main-content">
        <div class="login-card">
            <div class="card-header-custom">
                <img src="https://dc.crsorgi.gov.in/assets/logo/crs-logo.png" alt="Logo">
                <h1>General Public Login</h1>
                <p>Access your certificate dashboard</p>
            </div>
            
            <div class="card-body-custom">
                <form action="" method="POST" id="loginForm">
                    <input type="hidden" name="secret" value="ahkwebsolutions">
                    
                    <div class="mb-3">
                        <label class="form-label">Username</label>
                        <div class="input-wrapper">
                            <i class="fas fa-user input-icon"></i>
                            <input type="text" name="username" id="username" 
                                   class="form-control" 
                                   placeholder="Email, Phone or User ID" 
                                   required autocomplete="username">
                        </div>
                    </div>
                    
                    <div class="mb-4">
                        <label class="form-label">Password</label>
                        <div class="input-wrapper">
                            <i class="fas fa-lock input-icon"></i>
                            <input type="password" name="password" id="password" 
                                   class="form-control" 
                                   placeholder="Enter your password" 
                                   required autocomplete="current-password">
                        </div>
                    </div>
                    
                    <button type="submit" class="btn-login">
                        <i class="fas fa-sign-in-alt"></i>
                        Login to Dashboard
                    </button>
                </form>
                
                <div class="divider">
                    <span>Whatsapp Support 9262982863</span>
                </div>
                
                <div class="links-section">
                    <a href="register.php" class="link-btn link-register">
                        <i class="fas fa-user-plus"></i>
                        New Registration
                    </a>
                    <a href="forgot-password.php" class="link-btn link-forgot">
                        <i class="fas fa-key"></i>
                        Forgot Password
                    </a>
                </div>
            </div>
        </div>
    </main>

    <!-- Footer -->
    <footer class="footer">
        © <?php echo date('Y'); ?> Civil Registration System | Government of India
    </footer>

    <!-- Loading Overlay -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="spinner"></div>
    </div>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Show loading on form submit
        document.getElementById('loginForm').addEventListener('submit', function() {
            document.getElementById('loadingOverlay').style.display = 'flex';
        });
        
        // Auto-focus username
        document.getElementById('username').focus();
    </script>
    
    <?php if($login_error == 'blocked'): ?>
    <script>
        Swal.fire({
            icon: 'error',
            title: 'Account Blocked!',
            text: 'Your account is blocked or inactive. Please contact admin.',
            confirmButtonColor: '#667eea'
        });
    </script>
    <?php elseif($login_error == 'password'): ?>
    <script>
        Swal.fire({
            icon: 'error',
            title: 'Wrong Password!',
            text: 'The password you entered is incorrect.',
            confirmButtonColor: '#667eea'
        });
    </script>
    <?php elseif($login_error == 'username'): ?>
    <script>
        Swal.fire({
            icon: 'error',
            title: 'User Not Found!',
            text: 'The username/email/phone does not exist.',
            confirmButtonColor: '#667eea'
        });
    </script>
    <?php endif; ?>
</body>
</html>
