<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/common.php';
require_once __DIR__ . '/../includes/auth.php';

$admin = current_platform_admin();
if (!$admin) {
    redirect(base_url('admin/index.php'));
}

$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();

    $familyName = trim((string)($_POST['family_name'] ?? ''));
    $familySlug = trim((string)($_POST['family_slug'] ?? ''));
    $contactName = trim((string)($_POST['primary_contact_name'] ?? ''));
    $contactEmail = trim((string)($_POST['primary_contact_email'] ?? ''));
    $familyAdminName = trim((string)($_POST['family_admin_name'] ?? ''));
    $familyAdminUsername = trim((string)($_POST['family_admin_username'] ?? ''));
    $familyAdminPassword = (string)($_POST['family_admin_password'] ?? '');

    if (
        $familyName === '' ||
        $familySlug === '' ||
        $familyAdminName === '' ||
        $familyAdminUsername === '' ||
        $familyAdminPassword === ''
    ) {
        $error = 'Please fill in all required fields.';
    } else {
        try {
            $pdo = db();
            $pdo->beginTransaction();

            $slug = strtolower(trim($familySlug));
            $slug = preg_replace('/[^a-z0-9\-]/', '-', $slug);
            $slug = preg_replace('/-+/', '-', $slug);
            $slug = trim($slug, '-');

            $check = $pdo->prepare('SELECT id FROM families WHERE family_slug = ? LIMIT 1');
            $check->execute([$slug]);
            if ($check->fetch()) {
                throw new RuntimeException('That family slug is already in use.');
            }

            $stmt = $pdo->prepare('
                INSERT INTO families (family_name, family_slug, primary_contact_name, primary_contact_email, status)
                VALUES (?, ?, ?, ?, "active")
            ');
            $stmt->execute([$familyName, $slug, $contactName, $contactEmail]);

            $familyId = (int)$pdo->lastInsertId();

            $stmt = $pdo->prepare('
                INSERT INTO family_settings (family_id, max_caregiver_session, allow_indefinite)
                VALUES (?, "90", "no")
            ');
            $stmt->execute([$familyId]);

            $passwordHash = password_hash($familyAdminPassword, PASSWORD_DEFAULT);

            $stmt = $pdo->prepare('
                INSERT INTO family_admins (family_id, full_name, username, password_hash, is_active)
                VALUES (?, ?, ?, ?, 1)
            ');
            $stmt->execute([$familyId, $familyAdminName, $familyAdminUsername, $passwordHash]);

            $pdo->commit();
            $message = 'Family account created successfully.';
        } catch (Throwable $e) {
            if (isset($pdo) && $pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $error = $e->getMessage();
        }
    }
}

$families = [];
try {
    $stmt = db()->query('
        SELECT id, family_name, family_slug, status, primary_contact_name, primary_contact_email, created_at
        FROM families
        ORDER BY id DESC
    ');
    $families = $stmt->fetchAll();
} catch (Throwable $e) {
    $error = $error ?: 'Could not load family list.';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Platform Admin Dashboard</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f4f7fb;
            margin: 0;
            color: #1f2937;
        }
        .wrap {
            max-width: 1100px;
            margin: 0 auto;
            padding: 24px;
        }
        .topbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 12px;
            margin-bottom: 20px;
        }
        .card {
            background: #fff;
            border-radius: 14px;
            padding: 22px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.08);
            margin-bottom: 18px;
        }
        .grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 14px;
        }
        .field {
            display: flex;
            flex-direction: column;
            gap: 6px;
            margin-bottom: 14px;
        }
        label {
            font-weight: 700;
            font-size: 14px;
        }
        input {
            width: 100%;
            padding: 11px 12px;
            border: 1px solid #d1d5db;
            border-radius: 10px;
            box-sizing: border-box;
        }
        button, .logout-link {
            display: inline-block;
            padding: 11px 16px;
            background: #2563eb;
            color: #fff;
            border: none;
            border-radius: 10px;
            text-decoration: none;
            font-weight: 700;
            cursor: pointer;
        }
        .logout-link {
            background: #6b7280;
        }
        .msg {
            background: #dcfce7;
            color: #166534;
            padding: 12px;
            border-radius: 10px;
            margin-bottom: 14px;
        }
        .err {
            background: #fee2e2;
            color: #991b1b;
            padding: 12px;
            border-radius: 10px;
            margin-bottom: 14px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            text-align: left;
            padding: 10px;
            border-bottom: 1px solid #e5e7eb;
            vertical-align: top;
        }
        th {
            font-size: 13px;
            color: #374151;
            background: #f9fafb;
        }
        @media (max-width: 800px) {
            .grid {
                grid-template-columns: 1fr;
            }
            .topbar {
                flex-direction: column;
                align-items: flex-start;
            }
        }
    </style>
</head>
<body>
<div class="wrap">
    <div class="topbar">
        <div>
            <h1 style="margin:0;">Platform Admin Dashboard</h1>
            <div style="margin-top:6px;color:#6b7280;">Logged in as <?= htmlspecialchars($admin['username'] ?? 'admin') ?></div>
        </div>
        <a class="logout-link" href="<?= htmlspecialchars(base_url('admin/logout.php')) ?>">Log Out</a>
    </div>

    <div class="card">
        <h2 style="margin-top:0;">Create Family Account</h2>

        <?php if ($message): ?>
            <div class="msg"><?= htmlspecialchars($message) ?></div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="err"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <form method="POST">
            <?= csrf_input() ?>

            <div class="grid">
                <div class="field">
                    <label for="family_name">Family Name</label>
                    <input id="family_name" name="family_name" required>
                </div>
                <div class="field">
                    <label for="family_slug">Family Slug</label>
                    <input id="family_slug" name="family_slug" placeholder="smith-family" required>
                </div>
            </div>

            <div class="grid">
                <div class="field">
                    <label for="primary_contact_name">Primary Contact Name</label>
                    <input id="primary_contact_name" name="primary_contact_name">
                </div>
                <div class="field">
                    <label for="primary_contact_email">Primary Contact Email</label>
                    <input id="primary_contact_email" name="primary_contact_email" type="email">
                </div>
            </div>

            <h3>Initial Family Admin</h3>

            <div class="grid">
                <div class="field">
                    <label for="family_admin_name">Admin Full Name</label>
                    <input id="family_admin_name" name="family_admin_name" required>
                </div>
                <div class="field">
                    <label for="family_admin_username">Admin Username</label>
                    <input id="family_admin_username" name="family_admin_username" required>
                </div>
            </div>

            <div class="field">
                <label for="family_admin_password">Admin Password</label>
                <input id="family_admin_password" name="family_admin_password" type="password" required>
            </div>

            <button type="submit">Create Family</button>
        </form>
    </div>

    <div class="card">
        <h2 style="margin-top:0;">Existing Families</h2>

        <?php if (!$families): ?>
            <p style="margin:0;color:#6b7280;">No family accounts created yet.</p>
        <?php else: ?>
            <div style="overflow:auto;">
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Family</th>
                            <th>Slug</th>
                            <th>Status</th>
                            <th>Primary Contact</th>
                            <th>Email</th>
                            <th>Created</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($families as $family): ?>
                        <tr>
                            <td><?= (int)$family['id'] ?></td>
                            <td><?= htmlspecialchars($family['family_name']) ?></td>
                            <td><?= htmlspecialchars($family['family_slug']) ?></td>
                            <td><?= htmlspecialchars($family['status']) ?></td>
                            <td><?= htmlspecialchars((string)$family['primary_contact_name']) ?></td>
                            <td><?= htmlspecialchars((string)$family['primary_contact_email']) ?></td>
                            <td><?= htmlspecialchars((string)$family['created_at']) ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>
</body>
</html>