<?php
// Session Start
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once 'config/database.php';

$page_title = "Login / Register";

// যদি ইউজার আগে থেকেই লগইন থাকে
if(isset($_SESSION['is_user_logged_in']) && $_SESSION['is_user_logged_in'] === true) {
    header("Location: index.php");
    exit();
}

$error_msg = '';
$success_msg = '';
$active_tab = 'login'; 

// ==========================================
// 1. Safe Auto Create & Migrate Users Table
// ==========================================
try {
    $db->exec("CREATE TABLE IF NOT EXISTS `users` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `name` VARCHAR(100) NOT NULL,
        `email` VARCHAR(150) NOT NULL UNIQUE,
        `phone` VARCHAR(20) NULL,
        `company_name` VARCHAR(150) NULL,
        `address` TEXT NULL,
        `city` VARCHAR(50) NULL,
        `state` VARCHAR(50) NULL,
        `postcode` VARCHAR(20) NULL,
        `country` VARCHAR(50) DEFAULT 'Bangladesh',
        `password` VARCHAR(255) NOT NULL,
        `balance` DECIMAL(10,2) DEFAULT 0.00,
        `status` ENUM('active', 'suspended') DEFAULT 'active',
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");

    $new_columns = [
        'name' => "VARCHAR(100) NOT NULL AFTER `id`",
        'phone' => "VARCHAR(20) NULL AFTER `email`",
        'company_name' => "VARCHAR(150) NULL AFTER `phone`",
        'address' => "TEXT NULL AFTER `company_name`",
        'city' => "VARCHAR(50) NULL AFTER `address`",
        'state' => "VARCHAR(50) NULL AFTER `city`",
        'postcode' => "VARCHAR(20) NULL AFTER `state`",
        'country' => "VARCHAR(50) DEFAULT 'Bangladesh' AFTER `postcode`"
    ];

    foreach($new_columns as $col => $definition) {
        try {
            $db->exec("ALTER TABLE `users` ADD COLUMN `$col` $definition");
        } catch(PDOException $e) {}
    }
} catch(PDOException $e) {
    $error_msg = "Database Error: " . $e->getMessage();
}

// ==========================================
// 2. Handle Registration 
// ==========================================
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['register_submit'])) {
    $active_tab = 'register';
    $name     = trim($_POST['name']);
    $email    = trim($_POST['email']);
    $phone    = trim($_POST['phone']);
    $company  = trim($_POST['company_name']);
    $address  = trim($_POST['address']);
    $city     = trim($_POST['city']);
    $state    = trim($_POST['state']);
    $postcode = trim($_POST['postcode']);
    $country  = trim($_POST['country']);
    $password = $_POST['password'];

    if(!isset($_POST['terms_agreed'])) {
        $error_msg = "You must agree to our Terms of Service and Privacy Policy.";
    } elseif(empty($name) || empty($email) || empty($password) || empty($address) || empty($city)) {
        $error_msg = "Please fill in all required billing details!";
    } else {
        $stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->execute([$email]);
        if($stmt->rowCount() > 0) {
            $error_msg = "Email is already registered! Please login.";
        } else {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $insert = $db->prepare("INSERT INTO users (name, email, phone, company_name, address, city, state, postcode, country, password) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            
            if($insert->execute([$name, $email, $phone, $company, $address, $city, $state, $postcode, $country, $hashed_password])) {
                $success_msg = "Account created successfully! You can now login.";
                $active_tab = 'login'; 
            } else {
                $error_msg = "Registration failed. Please try again.";
            }
        }
    }
}

// ==========================================
// 3. Handle Login
// ==========================================
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['login_submit'])) {
    $email = trim($_POST['email']);
    $password = $_POST['password'];

    $stmt = $db->prepare("SELECT * FROM users WHERE email = ? LIMIT 1");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if($user && password_verify($password, $user['password'])) {
        if($user['status'] == 'suspended') {
            $error_msg = "Your account is suspended. Please contact support.";
        } else {
            $_SESSION['is_user_logged_in'] = true;
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_name'] = $user['name'];
            
            // Magic Redirect Logic (যেখান থেকে এসেছে, সেখানেই ফেরত যাবে)
            if(isset($_SESSION['redirect_url'])) {
                $redirect = $_SESSION['redirect_url'];
                unset($_SESSION['redirect_url']);
                header("Location: " . $redirect);
            } else {
                // সরাসরি লগইন করলে ড্যাশবোর্ডের বদলে index.php তে যাবে
                header("Location: index.php");
            }
            exit();
        }
    } else {
        $error_msg = "Invalid Email or Password!";
    }
}

require_once 'includes/user_header.php';
require_once 'includes/user_sidebar.php';
?>

<style>
    body {
        background-color: #ffffff !important;
        background-image: 
            linear-gradient(rgba(37, 99, 235, 0.025) 1px, transparent 1px),
            linear-gradient(90deg, rgba(37, 99, 235, 0.025) 1px, transparent 1px) !important;
        background-size: 30px 30px !important;
        color: #1e293b !important;
    }

    a { text-decoration: none !important; }

    .auth-container {
        background: #ffffff;
        border-radius: 24px;
        box-shadow: 0 20px 50px -10px rgba(37, 99, 235, 0.15);
        overflow: hidden;
        border: 1px solid rgba(37, 99, 235, 0.1);
        max-width: 1100px; 
        margin: 0 auto;
    }

    .auth-left { padding: 40px 50px; }
    @media (max-width: 768px) { .auth-left { padding: 30px 20px; } }
    
    .auth-logo { height: 45px; object-fit: contain; margin-bottom: 25px; }

    .auth-toggle-box {
        background: #f8fafc;
        border-radius: 50px;
        padding: 5px;
        display: flex;
        margin-bottom: 30px;
        border: 1px solid rgba(15, 23, 42, 0.05);
    }
    .toggle-btn {
        flex: 1;
        text-align: center;
        padding: 10px;
        border-radius: 50px;
        font-weight: 700;
        color: #64748b;
        cursor: pointer;
        transition: all 0.3s ease;
    }
    .toggle-btn.active {
        background: #2563eb;
        color: #ffffff;
        box-shadow: 0 5px 15px rgba(37, 99, 235, 0.3);
    }

    .form-control, .form-select {
        border-radius: 12px;
        padding: 12px 18px;
        border: 1px solid rgba(15, 23, 42, 0.1);
        background: #f8fafc;
        color: #0f172a;
        font-size: 15px;
        transition: all 0.3s;
    }
    .form-control:focus, .form-select:focus {
        background: #ffffff;
        border-color: #2563eb;
        box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.1);
    }
    .input-icon {
        position: absolute;
        right: 18px;
        top: 50%;
        transform: translateY(-50%);
        color: #94a3b8;
    }
    .form-label { font-size: 13px; font-weight: 600; color: #64748b; margin-bottom: 5px; }

    .btn-submit {
        background: #2563eb;
        color: white;
        border: none;
        width: 100%;
        padding: 14px;
        border-radius: 12px;
        font-weight: 700;
        font-size: 16px;
        box-shadow: 0 8px 20px rgba(37, 99, 235, 0.3);
        transition: all 0.3s;
        margin-top: 10px;
    }
    .btn-submit:hover { transform: translateY(-2px); box-shadow: 0 12px 25px rgba(37, 99, 235, 0.4); background: #1d4ed8; }

    .auth-right {
        background: linear-gradient(135deg, #1e3a8a, #2563eb, #8b5cf6);
        color: white;
        padding: 50px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        text-align: center;
        position: relative;
    }
    @media (max-width: 991px) { .auth-right { display: none !important; } }

    .auth-form { display: none; animation: fadeIn 0.4s ease forwards; }
    .auth-form.active { display: block; }
    @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }

    .terms-box {
        background: #f8fafc;
        border: 1px solid rgba(15, 23, 42, 0.1);
        padding: 15px;
        border-radius: 12px;
        margin-bottom: 20px;
    }
    .terms-link { color: #2563eb; font-weight: 600; text-decoration: none; }
    .terms-link:hover { text-decoration: underline; }
</style>

<!-- Main Content Area -->
<div class="main-content flex-grow-1 w-100 d-flex flex-column" style="min-height: calc(100vh - 70px); overflow-x: hidden;">
    
    <div class="flex-grow-1 d-flex align-items-center justify-content-center py-5 w-100">
        <div class="container">
            <div class="row auth-container mx-auto">
                
                <!-- Left Side: Forms -->
                <div class="col-lg-7 auth-left">
                    <h3 class="fw-bold mb-1">Welcome to <span style="color: #2563eb;">Client Area</span></h3>
                    <p class="text-muted mb-4" style="font-size: 15px;">Securely manage your hosting, domains, and billing.</p>

                    <?php if($error_msg): ?>
                        <div class="alert alert-danger shadow-sm border-0 py-2"><i class="fa-solid fa-circle-exclamation me-2"></i> <?= $error_msg ?></div>
                    <?php endif; ?>
                    <?php if($success_msg): ?>
                        <div class="alert alert-success shadow-sm border-0 py-2"><i class="fa-solid fa-circle-check me-2"></i> <?= $success_msg ?></div>
                    <?php endif; ?>

                    <div class="auth-toggle-box">
                        <div class="toggle-btn <?= $active_tab == 'login' ? 'active' : '' ?>" onclick="switchTab('login')">Sign In</div>
                        <div class="toggle-btn <?= $active_tab == 'register' ? 'active' : '' ?>" onclick="switchTab('register')">Create Account</div>
                    </div>

                    <!-- =====================================
                         LOGIN FORM 
                         ===================================== -->
                    <form action="" method="POST" id="loginForm" class="auth-form <?= $active_tab == 'login' ? 'active' : '' ?>">
                        <div class="mb-3 position-relative">
                            <label class="form-label">Email Address</label>
                            <input type="email" name="email" class="form-control" placeholder="example@gmail.com" required>
                            <i class="fa-solid fa-envelope input-icon"></i>
                        </div>
                        <div class="mb-3 position-relative">
                            <label class="form-label">Password</label>
                            <input type="password" name="password" class="form-control" placeholder="Enter your password" required>
                            <i class="fa-solid fa-lock input-icon"></i>
                        </div>
                        <div class="d-flex justify-content-between align-items-center mb-4 mt-3 px-1">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="rememberMe">
                                <label class="form-check-label text-muted fw-medium" for="rememberMe" style="font-size: 14px;">Remember me</label>
                            </div>
                            <a href="#" class="text-decoration-none fw-bold" style="font-size: 14px; color: #2563eb;">Forgot Password?</a>
                        </div>
                        <button type="submit" name="login_submit" class="btn-submit">Login to Dashboard <i class="fa-solid fa-arrow-right-to-bracket ms-2"></i></button>
                    </form>

                    <!-- =====================================
                         REGISTER FORM (WITH BILLING)
                         ===================================== -->
                    <form action="" method="POST" id="registerForm" class="auth-form <?= $active_tab == 'register' ? 'active' : '' ?>">
                        
                        <h6 class="fw-bold text-dark mb-3 border-bottom pb-2">Personal Information</h6>
                        <div class="row g-3 mb-4">
                            <div class="col-md-12 position-relative">
                                <input type="text" name="name" class="form-control" placeholder="Full Name *" required>
                                <i class="fa-solid fa-user input-icon"></i>
                            </div>
                            <div class="col-md-6 position-relative">
                                <input type="email" name="email" class="form-control" placeholder="Email Address *" required>
                                <i class="fa-solid fa-envelope input-icon"></i>
                            </div>
                            <div class="col-md-6 position-relative">
                                <input type="text" name="phone" class="form-control" placeholder="Phone Number *" required>
                                <i class="fa-solid fa-phone input-icon"></i>
                            </div>
                        </div>

                        <h6 class="fw-bold text-dark mb-3 border-bottom pb-2">Billing Address</h6>
                        <div class="row g-3 mb-4">
                            <div class="col-12 position-relative">
                                <input type="text" name="company_name" class="form-control" placeholder="Company Name (Optional)">
                                <i class="fa-solid fa-building input-icon"></i>
                            </div>
                            <div class="col-12 position-relative">
                                <input type="text" name="address" class="form-control" placeholder="Street Address *" required>
                                <i class="fa-solid fa-map-location-dot input-icon"></i>
                            </div>
                            <div class="col-md-4">
                                <input type="text" name="city" class="form-control" placeholder="City *" required>
                            </div>
                            <div class="col-md-4">
                                <input type="text" name="state" class="form-control" placeholder="State/Division *" required>
                            </div>
                            <div class="col-md-4">
                                <input type="text" name="postcode" class="form-control" placeholder="Postcode *" required>
                            </div>
                            <div class="col-12">
                                <select name="country" class="form-select" required>
                                    <option value="Bangladesh" selected>Bangladesh</option>
                                    <option value="India">India</option>
                                    <option value="United States">United States</option>
                                    <option value="United Kingdom">United Kingdom</option>
                                </select>
                            </div>
                        </div>

                        <h6 class="fw-bold text-dark mb-3 border-bottom pb-2">Account Security</h6>
                        <div class="mb-4 position-relative">
                            <input type="password" name="password" class="form-control" placeholder="Create a strong password *" required>
                            <i class="fa-solid fa-lock input-icon"></i>
                        </div>

                        <div class="terms-box">
                            <div class="form-check">
                                <input class="form-check-input mt-1" type="checkbox" name="terms_agreed" id="termsCheck" required>
                                <label class="form-check-label text-muted" for="termsCheck" style="font-size: 13px;">
                                    I have read and agree to the <a href="terms.php" class="terms-link" target="_blank">Terms of Service</a> and <a href="privacy.php" class="terms-link" target="_blank">Privacy Policy</a>. I consent to providing accurate billing information for domain registration.
                                </label>
                            </div>
                        </div>

                        <button type="submit" name="register_submit" class="btn-submit">Register Complete Account <i class="fa-solid fa-user-plus ms-2"></i></button>
                    </form>

                </div>

                <!-- Right Side: Branding (Hidden on mobile) -->
                <div class="col-lg-5 auth-right">
                    <i class="fa-solid fa-server fa-4x mb-4" style="color: rgba(255,255,255,0.9);"></i>
                    <h2 class="fw-bold mb-3">Your Gateway to<br>Digital Success</h2>
                    <p class="fs-6" style="color: rgba(255,255,255,0.8);">Experience blazing fast BDIX hosting, seamless domain registration, and 24/7 elite support tailored for your business.</p>
                    
                    <ul class="text-start mt-4" style="list-style: none; padding: 0; color: rgba(255,255,255,0.9); font-weight: 500;">
                        <li class="mb-3"><i class="fa-solid fa-circle-check text-warning me-2"></i> Instant Account Activation</li>
                        <li class="mb-3"><i class="fa-solid fa-circle-check text-warning me-2"></i> Secure Domain Management</li>
                        <li class="mb-3"><i class="fa-solid fa-circle-check text-warning me-2"></i> Easy Payment Integration</li>
                    </ul>
                </div>

            </div>
        </div>
    </div> 
</div> 

<!-- JS for Toggle Tabs -->
<script>
    function switchTab(tab) {
        document.getElementById('loginForm').classList.remove('active');
        document.getElementById('registerForm').classList.remove('active');
        
        let btns = document.querySelectorAll('.toggle-btn');
        btns.forEach(btn => btn.classList.remove('active'));

        document.getElementById(tab + 'Form').classList.add('active');
        event.target.classList.add('active');
    }
</script>

<?php require_once 'includes/user_footer.php'; ?>