<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/admin_auth.php';
require_once __DIR__ . '/../includes/admin_layout_top.php';

if (!isset($mysqli) && isset($conn)) {
    $mysqli = $conn;
}

function h($v): string {
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}

function tbl_exists(mysqli $db, string $table): bool {
    $safe = $db->real_escape_string($table);
    $res = $db->query("SHOW TABLES LIKE '{$safe}'");
    return $res && $res->num_rows > 0;
}

function col_exists(mysqli $db, string $table, string $col): bool {
    $safeTable = $db->real_escape_string($table);
    $safeCol   = $db->real_escape_string($col);
    $res = $db->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeCol}'");
    return $res && $res->num_rows > 0;
}

$msg = '';
$err = '';

$adminId = (int)($GLOBALS['ADMIN_ID'] ?? ($_SESSION['user_id'] ?? $_SESSION['admin_id'] ?? 0));
$usersTable = tbl_exists($mysqli, 'users') ? 'users' : (tbl_exists($mysqli, 'admins') ? 'admins' : '');

if ($usersTable === '') {
    $err = 'Users table not found.';
}

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

    if ($action === 'profile') {
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');

        if ($name === '') {
            $err = 'Name is required.';
        } else {
            $sets = [];
            $vals = [];
            $types = '';

            if (col_exists($mysqli, $usersTable, 'name')) {
                $sets[] = 'name=?';
                $vals[] = $name;
                $types .= 's';
            } elseif (col_exists($mysqli, $usersTable, 'full_name')) {
                $sets[] = 'full_name=?';
                $vals[] = $name;
                $types .= 's';
            }

            if (col_exists($mysqli, $usersTable, 'email')) {
                $sets[] = 'email=?';
                $vals[] = $email;
                $types .= 's';
            }

            if ($sets) {
                $vals[] = $adminId;
                $types .= 'i';

                $sql = "UPDATE `{$usersTable}` SET " . implode(',', $sets) . " WHERE id=? LIMIT 1";
                $stmt = $mysqli->prepare($sql);
                $stmt->bind_param($types, ...$vals);

                if ($stmt->execute()) {
                    $_SESSION['user_name'] = $name;
                    $_SESSION['admin_name'] = $name;
                    $GLOBALS['ADMIN_NAME'] = $name;
                    $msg = 'Profile updated successfully.';
                } else {
                    $err = 'Profile update failed.';
                }
                $stmt->close();
            }
        }
    }

    if ($action === 'password') {
        $password = trim($_POST['password'] ?? '');
        $confirm = trim($_POST['confirm_password'] ?? '');

        if ($password === '' || strlen($password) < 6) {
            $err = 'Password must be at least 6 characters.';
        } elseif ($password !== $confirm) {
            $err = 'Password confirmation does not match.';
        } else {
            $hash = password_hash($password, PASSWORD_DEFAULT);

            if (col_exists($mysqli, $usersTable, 'password')) {
                $col = 'password';
            } elseif (col_exists($mysqli, $usersTable, 'password_hash')) {
                $col = 'password_hash';
            } else {
                $col = '';
            }

            if ($col) {
                $stmt = $mysqli->prepare("UPDATE `{$usersTable}` SET `{$col}`=? WHERE id=? LIMIT 1");
                $stmt->bind_param('si', $hash, $adminId);

                if ($stmt->execute()) {
                    $msg = 'Password changed successfully.';
                } else {
                    $err = 'Password update failed.';
                }
                $stmt->close();
            } else {
                $err = 'Password column not found.';
            }
        }
    }
}

$profile = [
    'name' => $GLOBALS['ADMIN_NAME'] ?? 'Admin',
    'email' => '',
    'role' => $GLOBALS['ADMIN_ROLE'] ?? '',
];

if ($usersTable && $adminId > 0) {
    $select = ['id'];

    if (col_exists($mysqli, $usersTable, 'name')) {
        $select[] = 'name';
    } elseif (col_exists($mysqli, $usersTable, 'full_name')) {
        $select[] = 'full_name AS name';
    } else {
        $select[] = "'' AS name";
    }

    $select[] = col_exists($mysqli, $usersTable, 'email') ? 'email' : "'' AS email";

    if (col_exists($mysqli, $usersTable, 'role')) {
        $select[] = 'role';
    } elseif (col_exists($mysqli, $usersTable, 'admin_role')) {
        $select[] = 'admin_role AS role';
    } else {
        $select[] = "'' AS role";
    }

    $stmt = $mysqli->prepare("SELECT " . implode(',', $select) . " FROM `{$usersTable}` WHERE id=? LIMIT 1");
    $stmt->bind_param('i', $adminId);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res && $res->num_rows) {
        $profile = $res->fetch_assoc();
    }
    $stmt->close();
}
?>

<div class="container-fluid">
    <div class="d-flex flex-wrap justify-content-between align-items-center mb-4 gap-2">
        <div>
            <h4 class="mb-1">Profile</h4>
            <div class="text-muted small">Manage your admin account details.</div>
        </div>
    </div>

    <?php if ($msg): ?>
        <div class="alert alert-success"><?= h($msg) ?></div>
    <?php endif; ?>

    <?php if ($err): ?>
        <div class="alert alert-danger"><?= h($err) ?></div>
    <?php endif; ?>

    <div class="row g-4">
        <div class="col-lg-5">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center">
                    <div class="rounded-circle bg-primary text-white d-inline-flex align-items-center justify-content-center mb-3" style="width:86px;height:86px;font-size:32px;font-weight:700;">
                        <?= h(strtoupper(substr((string)($profile['name'] ?? 'A'), 0, 1))) ?>
                    </div>
                    <h5 class="mb-1"><?= h($profile['name'] ?? 'Admin') ?></h5>
                    <div class="text-muted mb-2"><?= h($profile['email'] ?? '') ?></div>
                    <span class="badge bg-dark"><?= h($profile['role'] ?? '') ?></span>
                </div>
            </div>
        </div>

        <div class="col-lg-7">
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-0">
                    <h6 class="mb-0">Profile Details</h6>
                </div>
                <div class="card-body">
                    <form method="post">
                        <input type="hidden" name="action" value="profile">

                        <div class="mb-3">
                            <label class="form-label">Name</label>
                            <input type="text" name="name" class="form-control" value="<?= h($profile['name'] ?? '') ?>" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Email</label>
                            <input type="email" name="email" class="form-control" value="<?= h($profile['email'] ?? '') ?>">
                        </div>

                        <button class="btn btn-primary">
                            <i class="bi bi-check-circle me-1"></i> Update Profile
                        </button>
                    </form>
                </div>
            </div>

            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-0">
                    <h6 class="mb-0">Change Password</h6>
                </div>
                <div class="card-body">
                    <form method="post">
                        <input type="hidden" name="action" value="password">

                        <div class="mb-3">
                            <label class="form-label">New Password</label>
                            <input type="password" name="password" class="form-control" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Confirm Password</label>
                            <input type="password" name="confirm_password" class="form-control" required>
                        </div>

                        <button class="btn btn-dark">
                            <i class="bi bi-shield-lock me-1"></i> Change Password
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/admin_layout_bottom.php'; ?>