<?php
require_once 'includes/config.php';

if (isLoggedIn()) { header('Location: ' . SITE_URL . '/dashboard.php'); exit; }

$error = ''; $success = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = sanitize($_POST['name'] ?? '');
    $username = sanitize($_POST['username'] ?? '');
    $email = sanitize($_POST['email'] ?? '');
    $phone = sanitize($_POST['phone'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm = $_POST['confirm_password'] ?? '';
    $ref = sanitize($_POST['referral'] ?? '');

    if (!$name || !$username || !$phone || !$password) {
        $error = 'সব তথ্য পূরণ করুন!';
    } elseif ($password !== $confirm) {
        $error = 'পাসওয়ার্ড মিলছে না!';
    } elseif (strlen($password) < 6) {
        $error = 'পাসওয়ার্ড কমপক্ষে ৬ অক্ষরের হতে হবে!';
    } else {
        $db = getDB();
        $check = $db->prepare("SELECT id FROM users WHERE username=? OR phone=? OR email=?");
        $check->execute([$username, $phone, $email]);
        if ($check->fetch()) {
            $error = 'এই ইউজারনেম, ফোন বা ইমেইল আগে থেকেই আছে!';
        } else {
            $reseller_id = null;
            if ($ref) {
                $rs = $db->prepare("SELECT id FROM users WHERE username=? AND role IN ('reseller','admin')");
                $rs->execute([$ref]);
                $reseller = $rs->fetch();
                if ($reseller) $reseller_id = $reseller['id'];
            }
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $regOpen = getSetting('registration_open');
            $status = ($regOpen == '1') ? 'active' : 'pending';
            $stmt = $db->prepare("INSERT INTO users (name,username,email,phone,password,reseller_id,status) VALUES (?,?,?,?,?,?,?)");
            $stmt->execute([$name,$username,$email,$phone,$hash,$reseller_id,$status]);
            $newUserId = $db->lastInsertId();

            // Create user_service_access table if not exists
            try {
                $db->exec("CREATE TABLE IF NOT EXISTS user_service_access (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    user_id INT NOT NULL,
                    service VARCHAR(30) NOT NULL,
                    is_enabled TINYINT(1) DEFAULT 1,
                    UNIQUE KEY uq_user_svc (user_id, service)
                )");
                // Apply default services from settings
                $svcKeys = ['topup','drive','international','cards','manual_drive','mbanking','deposit'];
                foreach($svcKeys as $s) {
                    $defaultOn = (getSetting('default_svc_'.$s) ?? '1') === '1' ? 1 : 0;
                    $db->prepare("INSERT IGNORE INTO user_service_access (user_id,service,is_enabled) VALUES (?,?,?)")
                       ->execute([$newUserId, $s, $defaultOn]);
                }
            } catch(Exception $e) {}

            $success = 'রেজিস্ট্রেশন সফল!';
            // Auto-login
            require_once 'includes/device_security.php';
            checkDeviceLogin($newUserId);
            $_SESSION['user_id']           = $newUserId;
            $_SESSION['role']              = 'user';
            $_SESSION['name']              = sanitize($_POST['name']??'');
            $_SESSION['last_activity']     = time();
            $_SESSION['device_token']      = getDeviceToken();
            $_SESSION['device_last_check'] = 0;
            header('Location: ' . SITE_URL . '/dashboard.php'); exit;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register - <?= SITE_NAME ?></title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        * { margin:0; padding:0; box-sizing:border-box; }
        :root { --primary:#1a3c8f; --secondary:#f5a623; --dark:#0d1f4e; }
        body { font-family:'Segoe UI',sans-serif; background:linear-gradient(135deg,var(--dark),var(--primary)); min-height:100vh; display:flex; align-items:center; justify-content:center; padding:20px; }
        .card { background:white; border-radius:20px; padding:35px; width:100%; max-width:450px; box-shadow:0 20px 60px rgba(0,0,0,0.3); }
        .logo { text-align:center; margin-bottom:25px; }
        .logo h1 { color:var(--primary); font-size:26px; font-weight:800; }
        .logo span { color:var(--secondary); }
        .logo p { color:#888; font-size:13px; }
        .form-row { display:grid; grid-template-columns:1fr 1fr; gap:15px; }
        .form-group { margin-bottom:16px; }
        label { display:block; color:#555; font-size:13px; margin-bottom:5px; font-weight:500; }
        .inp { position:relative; }
        .inp i { position:absolute; left:13px; top:50%; transform:translateY(-50%); color:#aaa; font-size:13px; }
        input { width:100%; padding:12px 12px 12px 38px; border:2px solid #e8ecf4; border-radius:10px; font-size:14px; outline:none; transition:0.2s; }
        input:focus { border-color:var(--primary); }
        .btn { width:100%; padding:13px; background:linear-gradient(135deg,var(--primary),#2856c8); color:white; border:none; border-radius:10px; font-size:15px; font-weight:600; cursor:pointer; }
        .btn:hover { transform:translateY(-1px); }
        .error { background:#fff0f0; color:#e53e3e; padding:10px; border-radius:8px; margin-bottom:15px; font-size:13px; border-left:4px solid #e53e3e; }
        .success { background:#f0fff4; color:#276749; padding:10px; border-radius:8px; margin-bottom:15px; font-size:13px; border-left:4px solid #38a169; }
        .link { text-align:center; margin-top:15px; font-size:13px; color:#666; }
        .link a { color:var(--primary); font-weight:600; text-decoration:none; }
    </style>
</head>
<body>
<div class="card">
    <div class="logo">
        <?php $_snp=explode(' ',trim(SITE_NAME),2); ?><h1><?= htmlspecialchars($_snp[0]) ?><?php if(isset($_snp[1])): ?> <span><?= htmlspecialchars($_snp[1]) ?></span><?php endif; ?></h1>
        <p>নতুন অ্যাকাউন্ট তৈরি করুন</p>
    </div>
    <?php if ($error): ?><div class="error"><i class="fas fa-times-circle"></i> <?= $error ?></div><?php endif; ?>
    <?php if ($success): ?><div class="success"><i class="fas fa-check-circle"></i> <?= $success ?> <a href="login.php">লগইন করুন</a></div><?php endif; ?>
    <?php if (!$success): ?>
    <form method="POST">
        <div class="form-row">
            <div class="form-group">
                <label>পূর্ণ নাম</label>
                <div class="inp"><i class="fas fa-user"></i><input type="text" name="name" placeholder="আপনার নাম" required></div>
            </div>
            <div class="form-group">
                <label>ইউজারনেম</label>
                <div class="inp"><i class="fas fa-at"></i><input type="text" name="username" placeholder="username" required></div>
            </div>
        </div>
        <div class="form-group">
            <label>ফোন নম্বর</label>
            <div class="inp"><i class="fas fa-phone"></i><input type="text" name="phone" placeholder="01XXXXXXXXX" required></div>
        </div>
        <div class="form-group">
            <label>ইমেইল (ঐচ্ছিক)</label>
            <div class="inp"><i class="fas fa-envelope"></i><input type="text" name="email" placeholder="email@example.com"></div>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label>পাসওয়ার্ড</label>
                <div class="inp"><i class="fas fa-lock"></i><input type="password" name="password" placeholder="••••••" required></div>
            </div>
            <div class="form-group">
                <label>কনফার্ম পাসওয়ার্ড</label>
                <div class="inp"><i class="fas fa-lock"></i><input type="password" name="confirm_password" placeholder="••••••" required></div>
            </div>
        </div>
        <div class="form-group">
            <label>রেফারেল কোড (ঐচ্ছিক)</label>
            <div class="inp"><i class="fas fa-gift"></i><input type="text" name="referral" placeholder="রিসেলারের ইউজারনেম"></div>
        </div>
        <button type="submit" class="btn">রেজিস্ট্রেশন করুন</button>
    </form>
    <?php endif; ?>
    <div class="link">আগে থেকে অ্যাকাউন্ট আছে? <a href="login.php">লগইন করুন</a></div>
</div>
</body>
</html>
