<?php
/**
 * Login Page
 * GHAMECC Choir Management Platform
 */

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if user is already logged in
if (isset($_SESSION['user_id'])) {
    // Redirect to dashboard
    header("Location: index.php");
    exit;
}

// Initialize variables
$error = '';
$username = '';
// Process login form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Include database connection
    require_once 'config/database.php';
    
    // Get form data
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    
    // Validate input
    if (empty($username) || empty($password)) {
        $error = "Please enter both username and password.";
    } else {
        // Query to find user
        $query = "SELECT u.id, u.username, u.password, u.full_name, r.role_key, u.profile_image,
                  u.society_id, u.circuit_id, u.diocese_id
                  FROM users u
                  LEFT JOIN roles r ON u.role_id = r.id
                  WHERE u.username = ? AND u.status = 'active'";
        
        // Prepare statement
        $stmt = $conn->prepare($query);
        if ($stmt === false) {
            $error = "Database error: " . $conn->error;
        } else {
            $stmt->bind_param("s", $username);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows === 1) {
                $user = $result->fetch_assoc();
                
                // Verify password
                if (password_verify($password, $user['password'])) {
                    // Update last login timestamp
                    $stmt = $conn->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
                    $stmt->bind_param("i", $user['id']);
                    $stmt->execute();
                    $stmt->close();
                    
                    // Get user's role information
                    $roleQuery = $conn->prepare("SELECT r.* FROM roles r WHERE r.id = ?");
                    $roleQuery->bind_param("i", $user['role_id']);
                    $roleQuery->execute();
                    $role = $roleQuery->get_result()->fetch_assoc();
                    $roleQuery->close();
                    
                    // Log successful login
                    if (function_exists('logInfo')) {
                        logInfo("User logged in successfully", [
                            'user_id' => $user['id'],
                            'username' => $user['username'],
                            'role' => $role ? $role['role_key'] : 'unknown'
                        ]);
                    }
                    
                    // Set session variables for entity IDs
                    $societyId = $user['society_id'];
                    $circuitId = $user['circuit_id'];
                    $dioceseId = $user['diocese_id'];
                    
                    // If entity IDs are not set in user record but user has a member_id,
                    // try to get entity IDs from the member record
                    if ((!$societyId || !$circuitId || !$dioceseId) && isset($user['member_id']) && $user['member_id']) {
                        $memberQuery = $conn->prepare("
                            SELECT 
                                m.society_id,
                                s.circuit_id,
                                c.diocese_id
                            FROM members m
                            LEFT JOIN societies s ON m.society_id = s.id
                            LEFT JOIN circuits c ON s.circuit_id = c.id
                            WHERE m.id = ?
                        ");
                        $memberQuery->bind_param("i", $user['member_id']);
                        $memberQuery->execute();
                        $memberData = $memberQuery->get_result()->fetch_assoc();
                        $memberQuery->close();
                        
                        if ($memberData) {
                            if (!$societyId && $memberData['society_id']) {
                                $societyId = $memberData['society_id'];
                                
                                // Update user record with society_id
                                $updateStmt = $conn->prepare("UPDATE users SET society_id = ? WHERE id = ?");
                                $updateStmt->bind_param("ii", $societyId, $user['id']);
                                $updateStmt->execute();
                                $updateStmt->close();
                            }
                            
                            if (!$circuitId && $memberData['circuit_id']) {
                                $circuitId = $memberData['circuit_id'];
                                
                                // Update user record with circuit_id
                                $updateStmt = $conn->prepare("UPDATE users SET circuit_id = ? WHERE id = ?");
                                $updateStmt->bind_param("ii", $circuitId, $user['id']);
                                $updateStmt->execute();
                                $updateStmt->close();
                            }
                            
                            if (!$dioceseId && $memberData['diocese_id']) {
                                $dioceseId = $memberData['diocese_id'];
                                
                                // Update user record with diocese_id
                                $updateStmt = $conn->prepare("UPDATE users SET diocese_id = ? WHERE id = ?");
                                $updateStmt->bind_param("ii", $dioceseId, $user['id']);
                                $updateStmt->execute();
                                $updateStmt->close();
                            }
                        }
                    }
                    
                    // Log entity IDs
                    if (function_exists('logInfo')) {
                        logInfo("User entity IDs", [
                            'user_id' => $user['id'],
                            'society_id' => $societyId,
                            'circuit_id' => $circuitId,
                            'diocese_id' => $dioceseId
                        ]);
                    }
                    
                    // Include authentication functions
                    require_once 'includes/auth.php';
                    
                    // Login user
                    loginUser(
                        $user['id'], 
                        $user['username'], 
                        $user['full_name'], 
                        $role ? $role['role_key'] : 'user', 
                        $user['profile_image'],
                        $societyId,
                        $circuitId,
                        $dioceseId
                    );
                    
                    // Redirect is handled by loginUser function
                } else {
                    $error = "Invalid username or password.";
                }
            } else {
                $error = "Invalid username or password.";
            }
            
            $stmt->close();
        }
        
        // Close connection
        $conn->close();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - GHAMECC Choir Management</title>
    
    <?php include 'includes/favicon.php'; ?>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Custom styles -->
    <style>
        body {
            background-color: #f8f9fa;
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .login-container {
            max-width: 400px;
            width: 100%;
            padding: 15px;
        }
        .card {
            border-radius: 1rem;
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
        }
        .card-header {
            background-color: #254094;
            color: white;
            text-align: center;
            border-radius: 1rem 1rem 0 0 !important;
            padding: 1.5rem;
        }
        .btn-primary {
            background-color: #254094;
            border-color: #254094;
        }
        .btn-primary:hover {
            background-color: #1f357b;
            border-color: #1b2f6b;
        }
        .btn-primary:focus,
        .btn-primary:active {
            background-color: #1b2f6b;
            border-color: #17295b;
            box-shadow: 0 0 0 0.25rem rgba(37, 64, 148, 0.35);
        }
        .logo {
            max-width: 150px;
            margin-bottom: 1rem;
        }
        .logo-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="card">
            <div class="card-header">
                <div class="logo-container">
                    <!-- Logo image - create an uploads/logo directory and place your logo there -->
                    <img src="includes/uploads/logo/ghamecclogooriginal.png" alt="GHAMECC Logo" class="logo">
                    <h4 class="mb-0">GHAMECC Choir Management</h4>
                    <p class="mb-0">Login to your account</p>
                </div>
            </div>
            <div class="card-body p-4">
                <?php if (!empty($error)): ?>
                    <div class="alert alert-danger" role="alert">
                        <?php echo htmlspecialchars($error); ?>
                    </div>
                <?php endif; ?>
                
                <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
                    <div class="mb-3">
                        <label for="username" class="form-label">Username</label>
                        <input type="text" class="form-control" id="username" name="username" 
                               value="<?php echo htmlspecialchars($username); ?>" required autofocus>
                    </div>
                    
                    <div class="mb-3">
                        <label for="password" class="form-label">Password</label>
                        <input type="password" class="form-control" id="password" name="password" required>
                    </div>
                    
                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-primary">Login</button>
                    </div>
                </form>
            </div>
            <div class="card-footer text-center py-3">
                <p class="mb-0">&copy; <?php echo date('Y'); ?> GHAMECC Choir Management</p>
            </div>
        </div>
    </div>
    
    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
