<?php
$pageTitle = 'Team Members';
require_once dirname(__DIR__) . '/includes/header.php';

db()->query("CREATE TABLE IF NOT EXISTS team_members (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    role VARCHAR(100),
    bio TEXT,
    photo VARCHAR(500),
    facebook VARCHAR(300),
    linkedin VARCHAR(300),
    sort_order INT DEFAULT 0,
    status ENUM('active','inactive') DEFAULT 'active',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

if (isset($_GET['delete'])) { db()->query("DELETE FROM team_members WHERE id=".(int)$_GET['delete']); flash('Deleted.','success'); redirect(ADMIN_URL.'/pages/team.php'); }

$error='';
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['action_add'])) {
    $n=trim($_POST['name']??''); $r=trim($_POST['role']??''); $b=trim($_POST['bio']??'');
    $fb=trim($_POST['facebook']??''); $li=trim($_POST['linkedin']??'');
    $s=(int)($_POST['sort_order']??0);
    $photo=handleUpload('photo','team')??trim($_POST['photo_url']??'');
    if(!$n){$error='Name required.';}
    else{
        $st=db()->prepare("INSERT INTO team_members (name,role,bio,photo,facebook,linkedin,sort_order) VALUES (?,?,?,?,?,?,?)");
        $st->bind_param('ssssssi',$n,$r,$b,$photo,$fb,$li,$s);
        $st->execute();
        flash('Team member added!','success');
        redirect(ADMIN_URL.'/pages/team.php');
    }
}
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['action_edit'])) {
    $id=(int)$_POST['edit_id'];
    $n=trim($_POST['name']??''); $r=trim($_POST['role']??''); $b=trim($_POST['bio']??'');
    $fb=trim($_POST['facebook']??''); $li=trim($_POST['linkedin']??'');
    $s=(int)($_POST['sort_order']??0); $status=$_POST['status']??'active';
    $ex=db()->query("SELECT photo FROM team_members WHERE id=$id")->fetch_assoc();
    $photo=handleUpload('photo','team')??trim($_POST['photo_url']??$ex['photo']??'');
    $st=db()->prepare("UPDATE team_members SET name=?,role=?,bio=?,photo=?,facebook=?,linkedin=?,sort_order=?,status=? WHERE id=?");
    $st->bind_param('ssssssssi',$n,$r,$b,$photo,$fb,$li,$s,$status,$id);
    $st->execute();
    flash('Updated!','success');
    redirect(ADMIN_URL.'/pages/team.php');
}

$members = db()->query("SELECT * FROM team_members ORDER BY sort_order,id")->fetch_all(MYSQLI_ASSOC);
$editItem = isset($_GET['edit']) ? db()->query("SELECT * FROM team_members WHERE id=".(int)$_GET['edit'])->fetch_assoc() : null;
?>
<div class="page-header"><h1>Team Members</h1><div class="page-header-actions"><button onclick="document.getElementById('addModal').classList.add('open')" class="btn btn-primary"><i class="fas fa-plus"></i> Add Member</button></div></div>
<?php if($error): ?><div class="flash flash-error"><?=e($error)?></div><?php endif; ?>

<?php if($editItem): ?>
<div class="card" style="margin-bottom:20px;border:2px solid var(--brand)">
    <div class="card-header"><i class="fas fa-edit" style="color:var(--brand)"></i><h2>Edit — <?=e($editItem['name'])?></h2><a href="team.php" class="btn btn-secondary btn-sm" style="margin-left:auto">Cancel</a></div>
    <div class="card-body">
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="edit_id" value="<?=$editItem['id']?>">
            <div class="form-row">
                <div class="form-group"><label class="form-label">Full Name *</label><input type="text" name="name" class="form-control" value="<?=e($editItem['name'])?>" required></div>
                <div class="form-group"><label class="form-label">Role / Position</label><input type="text" name="role" class="form-control" value="<?=e($editItem['role'])?>" placeholder="Senior Counselor"></div>
            </div>
            <div class="form-group"><label class="form-label">Bio</label><textarea name="bio" class="form-control" rows="3"><?=e($editItem['bio'])?></textarea></div>
            <div class="form-row">
                <div class="form-group"><label class="form-label">Replace Photo</label><input type="file" name="photo" class="form-control" accept="image/*"><?php if($editItem['photo']): ?><img src="<?=e(SITE_URL.'/'.$editItem['photo'])?>" style="margin-top:8px;width:60px;height:60px;border-radius:50%;object-fit:cover"><?php endif; ?></div>
                <div class="form-group"><label class="form-label">Or Photo URL</label><input type="text" name="photo_url" class="form-control" value="<?=e($editItem['photo'])?>"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label class="form-label">Facebook URL</label><input type="url" name="facebook" class="form-control" value="<?=e($editItem['facebook'])?>"></div>
                <div class="form-group"><label class="form-label">LinkedIn URL</label><input type="url" name="linkedin" class="form-control" value="<?=e($editItem['linkedin'])?>"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label class="form-label">Status</label><select name="status" class="form-select"><option value="active" <?=$editItem['status']==='active'?'selected':''?>>Active</option><option value="inactive" <?=$editItem['status']==='inactive'?'selected':''?>>Inactive</option></select></div>
                <div class="form-group"><label class="form-label">Sort Order</label><input type="number" name="sort_order" class="form-control" value="<?=(int)$editItem['sort_order']?>"></div>
            </div>
            <button type="submit" name="action_edit" class="btn btn-primary"><i class="fas fa-save"></i> Save</button>
        </form>
    </div>
</div>
<?php endif; ?>

<div class="card">
    <div class="card-header"><i class="fas fa-users" style="color:var(--brand)"></i><h2>All Team Members</h2><span style="color:var(--muted);font-size:13px;margin-left:auto"><?=count($members)?> members</span></div>
    <div class="table-wrap">
        <?php if(empty($members)): ?><div style="padding:40px;text-align:center;color:var(--muted)">No team members yet.</div>
        <?php else: ?>
        <table><thead><tr><th>Photo</th><th>Name</th><th>Role</th><th>Status</th><th>Actions</th></tr></thead><tbody>
        <?php foreach($members as $m): ?>
        <tr>
            <td><?php if($m['photo']): ?><img src="<?=e(SITE_URL.'/'.$m['photo'])?>" style="width:44px;height:44px;border-radius:50%;object-fit:cover"><?php else: ?><div style="width:44px;height:44px;border-radius:50%;background:var(--brand);display:flex;align-items:center;justify-content:center;color:#fff;font-weight:700"><?=strtoupper(substr($m['name'],0,1))?></div><?php endif; ?></td>
            <td style="font-weight:600"><?=e($m['name'])?></td>
            <td style="color:var(--muted)"><?=e($m['role'])?></td>
            <td><span class="badge <?=$m['status']==='active'?'badge-green':'badge-yellow'?>"><?=ucfirst($m['status'])?></span></td>
            <td><div style="display:flex;gap:5px">
                <a href="?edit=<?=$m['id']?>" class="btn btn-secondary btn-sm btn-icon"><i class="fas fa-edit"></i></a>
                <button onclick="confirmDelete('team.php?delete=<?=$m['id']?>','<?=e(addslashes($m['name']))?>')" class="btn btn-danger btn-sm btn-icon"><i class="fas fa-trash"></i></button>
            </div></td>
        </tr>
        <?php endforeach; ?>
        </tbody></table>
        <?php endif; ?>
    </div>
</div>

<div class="modal-overlay" id="addModal" onclick="if(event.target===this)this.classList.remove('open')">
    <div class="modal-box" style="max-width:520px">
        <div class="modal-title"><i class="fas fa-user-plus" style="color:var(--brand)"></i> Add Team Member</div>
        <form method="POST" enctype="multipart/form-data">
            <div class="form-row"><div class="form-group"><label class="form-label">Full Name *</label><input type="text" name="name" class="form-control" required placeholder="Shahria Shawn"></div><div class="form-group"><label class="form-label">Role</label><input type="text" name="role" class="form-control" placeholder="CEO & Founder"></div></div>
            <div class="form-group"><label class="form-label">Bio</label><textarea name="bio" class="form-control" rows="2" placeholder="Brief description..."></textarea></div>
            <div class="form-row"><div class="form-group"><label class="form-label">Upload Photo</label><input type="file" name="photo" class="form-control" accept="image/*"></div><div class="form-group"><label class="form-label">Or Photo URL</label><input type="text" name="photo_url" class="form-control" placeholder="https://..."></div></div>
            <div class="form-row"><div class="form-group"><label class="form-label">Facebook</label><input type="url" name="facebook" class="form-control" placeholder="https://facebook.com/..."></div><div class="form-group"><label class="form-label">LinkedIn</label><input type="url" name="linkedin" class="form-control"></div></div>
            <div class="form-group"><label class="form-label">Sort Order</label><input type="number" name="sort_order" class="form-control" value="0"></div>
            <div class="modal-btns"><button type="button" onclick="document.getElementById('addModal').classList.remove('open')" class="btn btn-secondary">Cancel</button><button type="submit" name="action_add" class="btn btn-primary"><i class="fas fa-save"></i> Add</button></div>
        </form>
    </div>
</div>
<?php require_once dirname(__DIR__) . '/includes/footer.php'; ?>
