<?php
session_start();
require 'db_connect.php';

// ---------- helpers ----------
function safe($v){ return htmlspecialchars((string)$v ?? '', ENT_QUOTES, 'UTF-8'); }
function redirect_to_index_then_exit(){
    header("Location: index2.html");
    exit();
}

// Track which tab to show
$activeTab = 'login'; // default

// Containers for errors and old values
$errors = [
    'login' => [],
    'register' => []
];
$old = [
    'login' => ['user_or_email' => ''],
    'register' => ['full_name'=>'','username'=>'','email'=>'']
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // ------------------ LOGIN ------------------
    if ($action === 'login') {
        $activeTab = 'login';
        $userOrEmail = trim($_POST['user_or_email'] ?? '');
        $password = $_POST['password'] ?? '';

        $old['login']['user_or_email'] = $userOrEmail;

        if ($userOrEmail === '') {
            $errors['login']['user_or_email'] = 'Please enter your username or email.';
        }
        if ($password === '') {
            $errors['login']['password'] = 'Please enter your password.';
        }

        if (!$errors['login']) {
            // Lookup by username OR email
            $stmt = $conn->prepare("SELECT * FROM Users WHERE username=? OR email=? LIMIT 1");
            $stmt->bind_param("ss", $userOrEmail, $userOrEmail);
            $stmt->execute();
            $res = $stmt->get_result();
            $user = $res->fetch_assoc();

            if ($user && password_verify($password, $user['password_hash'])) {
                // Optional: check is_active
                if (isset($user['is_active']) && !$user['is_active']) {
                    $errors['login']['user_or_email'] = 'Your account is inactive. Contact support.';
                } else {
                    // Update last_login_at
                    $now = date('Y-m-d H:i:s');
                    $up = $conn->prepare("UPDATE Users SET last_login_at=? WHERE user_id=?");
                    $up->bind_param("si", $now, $user['user_id']);
                    $up->execute();

                    $_SESSION['user_id'] = $user['user_id'];
                    $_SESSION['username'] = $user['username'];
                    redirect_to_index_then_exit();
                }
            } else {
                $errors['login']['user_or_email'] = 'Invalid username/email or password.';
                $errors['login']['password'] = 'Please try again.';
            }
        }
    }

    // ---------------- REGISTER -----------------
    if ($action === 'register') {
        $activeTab = 'register';

        $full_name = trim($_POST['full_name'] ?? '');
        $username  = trim($_POST['username'] ?? '');
        $email     = trim($_POST['email'] ?? '');
        $password  = $_POST['password'] ?? '';
        $confirm   = $_POST['confirm_password'] ?? '';

        $old['register'] = [
            'full_name' => $full_name,
            'username'  => $username,
            'email'     => $email,
        ];

        // Basic validations
        if ($full_name === '') {
            $errors['register']['full_name'] = 'Full name is required.';
        }
        if ($username === '') {
            $errors['register']['username'] = 'Username is required.';
        } elseif (!preg_match('/^[A-Za-z0-9._-]{3,}$/', $username)) {
            $errors['register']['username'] = 'Username should be 3+ chars (letters, numbers, . _ -).';
        }

        if ($email === '') {
            $errors['register']['email'] = 'Email is required.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors['register']['email'] = 'Please enter a valid email address.';
        }

        if ($password === '') {
            $errors['register']['password'] = 'Password is required.';
        } elseif (strlen($password) < 6) {
            $errors['register']['password'] = 'Use at least 6 characters.';
        }

        if ($confirm === '') {
            $errors['register']['confirm_password'] = 'Please confirm your password.';
        } elseif ($password !== $confirm) {
            $errors['register']['confirm_password'] = 'Passwords do not match.';
        }

        // Check duplicates only if no basic errors
        if (!$errors['register']) {
            $check = $conn->prepare("SELECT user_id FROM Users WHERE username=? OR email=? LIMIT 1");
            $check->bind_param("ss", $username, $email);
            $check->execute();
            $dupe = $check->get_result()->fetch_assoc();
            if ($dupe) {
                // Decide which field conflicts
                $checkU = $conn->prepare("SELECT user_id FROM Users WHERE username=? LIMIT 1");
                $checkU->bind_param("s", $username);
                $checkU->execute();
                if ($checkU->get_result()->fetch_assoc()) {
                    $errors['register']['username'] = 'This username is already taken.';
                }
                $checkE = $conn->prepare("SELECT user_id FROM Users WHERE email=? LIMIT 1");
                $checkE->bind_param("s", $email);
                $checkE->execute();
                if ($checkE->get_result()->fetch_assoc()) {
                    $errors['register']['email'] = 'This email is already registered.';
                }
            }
        }

        if (!$errors['register']) {
            $hash = password_hash($password, PASSWORD_DEFAULT);

            // Optional: store full_name somewhere. If you want to keep it,
            // either add a column full_name to Users or reuse username = full_name when desired.
            // Here we’ll keep username separate and ignore full_name unless you add a column.

            $stmt = $conn->prepare("INSERT INTO Users (username, email, password_hash, created_at) VALUES (?, ?, ?, NOW())");
            $stmt->bind_param("sss", $username, $email, $hash);

            if ($stmt->execute()) {
                $_SESSION['flash_success'] = 'Registration successful! Please log in.';
                $activeTab = 'login'; // switch to login tab after success
                // Clear old register values
                $old['register'] = ['full_name'=>'','username'=>'','email'=>''];
            } else {
                $_SESSION['flash_error'] = 'Something went wrong while creating your account. Please try again.';
                $activeTab = 'register';
            }
        }
    }
}

// Helper for setting invalid class
function invalidClass($arr, $key){
    return isset($arr[$key]) ? ' is-invalid' : '';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login & Register</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Custom CSS (unchanged) -->
    <style>
        body {
            background: linear-gradient(135deg, #4e73df, #1cc88a);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .card {
            border-radius: 1rem;
            box-shadow: 0 4px 20px rgba(0,0,0,0.15);
        }
        .form-control {
            border-radius: 0.5rem;
            padding: 0.75rem 1rem;
        }
        .btn-custom {
            border-radius: 0.5rem;
            padding: 0.75rem;
            font-weight: 600;
        }
        .tab-content { padding-top: 1rem; }
        .title-heading {
            color: #007bff;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="row justify-content-center">
        <div class="col-lg-5 col-md-7 col-sm-10">
            <div class="card p-4">
                <!-- Title -->
                <h3 class="text-center mb-3 title-heading">HALELUYA TV PARTNERS</h3>

                <?php if (!empty($_SESSION['flash_success'])): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?php echo safe($_SESSION['flash_success']); unset($_SESSION['flash_success']); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                <?php if (!empty($_SESSION['flash_error'])): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo safe($_SESSION['flash_error']); unset($_SESSION['flash_error']); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <!-- Tabs -->
                <ul class="nav nav-tabs justify-content-center" id="authTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link <?php echo $activeTab==='login' ? 'active' : ''; ?>" id="login-tab" data-bs-toggle="tab" data-bs-target="#login" type="button" role="tab">Login</button>
                    </li>
 
                </ul>

                <!-- Forms -->
                <div class="tab-content" id="authTabsContent">
                    
                    <!-- Login Form -->
                    <div class="tab-pane fade <?php echo $activeTab==='login' ? 'show active' : ''; ?>" id="login" role="tabpanel">
                        <h4 class="text-center mb-3">Welcome ...</h4>
                        <form method="post" novalidate>
                            <input type="hidden" name="action" value="login">
                            <div class="mb-3">
                                <label for="loginUserOrEmail" class="form-label">Username or Email</label>
                                <input type="text" class="form-control<?php echo invalidClass($errors['login'], 'user_or_email'); ?>" id="loginUserOrEmail" name="user_or_email" placeholder="Enter username or email" value="<?php echo safe($old['login']['user_or_email']); ?>">
                                <?php if(isset($errors['login']['user_or_email'])): ?>
                                    <div class="invalid-feedback"><?php echo safe($errors['login']['user_or_email']); ?></div>
                                <?php endif; ?>
                            </div>
                            <div class="mb-3">
                                <label for="loginPassword" class="form-label">Password</label>
                                <input type="password" class="form-control<?php echo invalidClass($errors['login'], 'password'); ?>" id="loginPassword" name="password" placeholder="Enter your password">
                                <?php if(isset($errors['login']['password'])): ?>
                                    <div class="invalid-feedback"><?php echo safe($errors['login']['password']); ?></div>
                                <?php endif; ?>
                            </div>
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <div>
                                    <input class="form-check-input" type="checkbox" id="rememberMe" disabled>
                                    <label class="form-check-label" for="rememberMe">Remember me</label>
                                </div>
                                <a href="#" class="text-decoration-none" title="Contact admin to reset">Forgot Password?</a>
                            </div>
                            <button type="submit" class="btn btn-primary w-100 btn-custom">Login</button>
                        </form>
                    </div>
                    
                    <!-- Register Form -->
                    <div class="tab-pane fade <?php echo $activeTab==='register' ? 'show active' : ''; ?>" id="register" role="tabpanel">
                        <h4 class="text-center mb-3">Create Account</h4>
                        <form method="post" novalidate>
                            <input type="hidden" name="action" value="register">
                            <div class="mb-3">
                                <label for="regName" class="form-label">Full Name</label>
                                <input type="text" class="form-control<?php echo invalidClass($errors['register'], 'full_name'); ?>" id="regName" name="full_name" placeholder="Enter your full name" value="<?php echo safe($old['register']['full_name']); ?>">
                                <?php if(isset($errors['register']['full_name'])): ?>
                                    <div class="invalid-feedback"><?php echo safe($errors['register']['full_name']); ?></div>
                                <?php endif; ?>
                            </div>
                            <div class="mb-3">
                                <label for="regUsername" class="form-label">Username</label>
                                <input type="text" class="form-control<?php echo invalidClass($errors['register'], 'username'); ?>" id="regUsername" name="username" placeholder="Choose a username" value="<?php echo safe($old['register']['username']); ?>">
                                <?php if(isset($errors['register']['username'])): ?>
                                    <div class="invalid-feedback"><?php echo safe($errors['register']['username']); ?></div>
                                <?php endif; ?>
                            </div>
                            <div class="mb-3">
                                <label for="regEmail" class="form-label">Email address</label>
                                <input type="email" class="form-control<?php echo invalidClass($errors['register'], 'email'); ?>" id="regEmail" name="email" placeholder="Enter your email" value="<?php echo safe($old['register']['email']); ?>">
                                <?php if(isset($errors['register']['email'])): ?>
                                    <div class="invalid-feedback"><?php echo safe($errors['register']['email']); ?></div>
                                <?php endif; ?>
                            </div>
                            <div class="mb-3">
                                <label for="regPassword" class="form-label">Password</label>
                                <input type="password" class="form-control<?php echo invalidClass($errors['register'], 'password'); ?>" id="regPassword" name="password" placeholder="Create a password">
                                <?php if(isset($errors['register']['password'])): ?>
                                    <div class="invalid-feedback"><?php echo safe($errors['register']['password']); ?></div>
                                <?php endif; ?>
                            </div>
                            <div class="mb-3">
                                <label for="regConfirmPassword" class="form-label">Confirm Password</label>
                                <input type="password" class="form-control<?php echo invalidClass($errors['register'], 'confirm_password'); ?>" id="regConfirmPassword" name="confirm_password" placeholder="Confirm password">
                                <?php if(isset($errors['register']['confirm_password'])): ?>
                                    <div class="invalid-feedback"><?php echo safe($errors['register']['confirm_password']); ?></div>
                                <?php endif; ?>
                            </div>
                            <button type="submit" class="btn btn-success w-100 btn-custom">Register</button>
                        </form>
                    </div>
                </div>

                <p class="text-center mt-3 text-muted small">© 2025 Alvy Info-Tech Company Ltd. All Rights Reserved.</p>
            </div>
        </div>
    </div>
</div>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
