<?php
session_start();
require_once '../connect.php';

$error=''; $success='';
if (isset($_GET['logout'])) { unset($_SESSION['super_admin_id']); header('Location: index.php'); exit; }

if (isset($_POST['admin_login'])) {
    $email = sanitize($conn, $_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $q = $conn->query("SELECT * FROM users WHERE email='$email' LIMIT 1");
    $u = ($q && $q->num_rows) ? $q->fetch_assoc() : null;
    $isSuper = $u && ((isset($u['is_super_admin']) && (int)$u['is_super_admin']===1) || (int)$u['id']===1);
    if ($isSuper && password_verify($password, $u['password'])) {
        $_SESSION['super_admin_id'] = $u['id'];
        $_SESSION['super_admin_name'] = $u['name'];
        header('Location: index.php'); exit;
    }
    $error='Invalid big admin login';
}

if (isset($_POST['create_account']) && !empty($_SESSION['super_admin_id'])) {
    $client = sanitize($conn, $_POST['client_name'] ?? '');
    $business = sanitize($conn, $_POST['business_name'] ?? '');
    $phone = sanitize($conn, $_POST['phone'] ?? '');
    $email = sanitize($conn, $_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    if (!$client || !$business || !$email || strlen($password)<6) {
        $error='Client, business, email and password 6+ chars are required';
    } else {
        $chk=$conn->query("SELECT id FROM users WHERE email='$email' LIMIT 1");
        if ($chk && $chk->num_rows) $error='Owner email already exists';
        else {
            $conn->query("INSERT INTO accounts (client_name,business_name,phone,email,status,currency) VALUES ('$client','$business','$phone','$email','active','USD')");
            $accountId=(int)$conn->insert_id;
            createDefaultStages($conn, $accountId);
            $roleName='Administrator'; $perms=$conn->real_escape_string(json_encode(['all'=>true]));
            $conn->query("INSERT INTO roles (name,permissions,account_id) VALUES ('$roleName','$perms',$accountId)");
            $roleId=(int)$conn->insert_id;
            $hash=$conn->real_escape_string(password_hash($password, PASSWORD_DEFAULT));
            $superCols = columnExists($conn,'users','is_account_owner') ? ', is_account_owner' : '';
            $superVals = columnExists($conn,'users','is_account_owner') ? ', 1' : '';
            $conn->query("INSERT INTO users (name,phone,email,password,role_id,account_id$superCols) VALUES ('$client','$phone','$email','$hash',$roleId,$accountId$superVals)");
            $userId=(int)$conn->insert_id;
            grantFullPermissions($conn, $accountId, $userId);
            $success="Account created. Owner user has full access.";
        }
    }
}
$logged = !empty($_SESSION['super_admin_id']);
$accounts = $logged ? $conn->query("SELECT a.*, (SELECT COUNT(*) FROM users u WHERE u.account_id=a.id) users_count FROM accounts a ORDER BY a.id DESC") : null;
?>
<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Shark CRM Big Admin</title><link rel="stylesheet" href="../assets/css/style.css"><style>body{background:#f6f8fb}.admin-wrap{max-width:1100px;margin:30px auto;padding:16px}.admin-card{background:#fff;border:1px solid var(--border);border-radius:18px;padding:22px;box-shadow:0 8px 30px rgba(15,23,42,.08)}.admin-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px}@media(max-width:800px){.admin-grid{grid-template-columns:1fr}.admin-wrap{margin:0;padding:12px}}</style></head><body><div class="admin-wrap">
<div class="admin-card">
<h2>🦈 Shark CRM Big Admin</h2>
<?php if($error): ?><div class="login-error"><?= htmlspecialchars($error) ?></div><?php endif; ?>
<?php if($success): ?><div style="background:#dcfce7;color:#166534;padding:12px;border-radius:10px;margin:10px 0"><?= htmlspecialchars($success) ?></div><?php endif; ?>
<?php if(!$logged): ?>
<form method="post" class="admin-grid"><input type="hidden" name="admin_login" value="1"><div class="form-group"><label class="form-label">Email</label><input class="form-control" type="email" name="email" required></div><div class="form-group"><label class="form-label">Password</label><input class="form-control" type="password" name="password" required></div><button class="btn btn-primary">Login</button></form>
<?php else: ?>
<div style="display:flex;justify-content:space-between;gap:10px;align-items:center"><p>Hello, <?= htmlspecialchars($_SESSION['super_admin_name'] ?? 'Admin') ?></p><a class="btn btn-secondary" href="?logout=1">Logout</a></div>
<h3>Create Account</h3>
<form method="post" class="admin-grid"><input type="hidden" name="create_account" value="1"><div class="form-group"><label class="form-label">Client Name</label><input class="form-control" name="client_name" required></div><div class="form-group"><label class="form-label">Business Name</label><input class="form-control" name="business_name" required></div><div class="form-group"><label class="form-label">Owner Email</label><input class="form-control" type="email" name="email" required></div><div class="form-group"><label class="form-label">Phone</label><input class="form-control" name="phone"></div><div class="form-group"><label class="form-label">Owner Password</label><input class="form-control" type="password" name="password" minlength="6" required></div><div style="align-self:end"><button class="btn btn-primary">Create Account + Owner Full Access</button></div></form>
<h3 style="margin-top:24px">Accounts</h3><div class="table-wrapper"><table class="crm-table"><thead><tr><th>ID</th><th>Business</th><th>Client</th><th>Email</th><th>Status</th><th>Users</th></tr></thead><tbody><?php while($a=$accounts->fetch_assoc()): ?><tr><td><?= $a['id'] ?></td><td><?= htmlspecialchars($a['business_name']) ?></td><td><?= htmlspecialchars($a['client_name']) ?></td><td><?= htmlspecialchars($a['email']) ?></td><td><?= htmlspecialchars($a['status']) ?></td><td><?= $a['users_count'] ?></td></tr><?php endwhile; ?></tbody></table></div>
<?php endif; ?>
</div></div></body></html>
