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

// Ensure table exists
db()->query("CREATE TABLE IF NOT EXISTS testimonials (
    id INT AUTO_INCREMENT PRIMARY KEY,
    student_name VARCHAR(100) NOT NULL,
    destination VARCHAR(100),
    university VARCHAR(200),
    review TEXT NOT NULL,
    photo VARCHAR(500),
    avatar_color VARCHAR(30) DEFAULT '#1a56db',
    flag_emoji VARCHAR(10),
    rating TINYINT DEFAULT 5,
    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 testimonials WHERE id=".(int)$_GET['delete']);
    flash('Testimonial deleted.','success');
    redirect(ADMIN_URL.'/pages/testimonials.php');
}
if (isset($_GET['toggle'])) {
    $t = db()->query("SELECT status FROM testimonials WHERE id=".(int)$_GET['toggle'])->fetch_assoc();
    $ns = $t['status']==='active'?'inactive':'active';
    db()->query("UPDATE testimonials SET status='$ns' WHERE id=".(int)$_GET['toggle']);
    flash('Status updated.','success');
    redirect(ADMIN_URL.'/pages/testimonials.php');
}

$error = '';
// Add
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['action_add'])) {
    $n=$_POST['student_name']??''; $d=$_POST['destination']??''; $u=$_POST['university']??'';
    $r=trim($_POST['review']??''); $f=$_POST['flag_emoji']??''; $c=$_POST['avatar_color']??'#1a56db';
    $s=(int)($_POST['sort_order']??0); $rating=(int)($_POST['rating']??5);
    $photo = handleUpload('photo','testimonials') ?? trim($_POST['photo_url']??'');
    if (!$n||!$r){$error='Name and review are required.';}
    else {
        $st=db()->prepare("INSERT INTO testimonials (student_name,destination,university,review,photo,flag_emoji,avatar_color,rating,sort_order) VALUES (?,?,?,?,?,?,?,?,?)");
        $st->bind_param('sssssssii',$n,$d,$u,$r,$photo,$f,$c,$rating,$s);
        $st->execute();
        flash('Testimonial added!','success');
        redirect(ADMIN_URL.'/pages/testimonials.php');
    }
}
// Edit
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['action_edit'])) {
    $id=(int)$_POST['edit_id'];
    $n=$_POST['student_name']??''; $d=$_POST['destination']??''; $u=$_POST['university']??'';
    $r=trim($_POST['review']??''); $f=$_POST['flag_emoji']??''; $c=$_POST['avatar_color']??'#1a56db';
    $s=(int)($_POST['sort_order']??0); $rating=(int)($_POST['rating']??5); $status=$_POST['status']??'active';
    $ex=db()->query("SELECT photo FROM testimonials WHERE id=$id")->fetch_assoc();
    $photo=handleUpload('photo','testimonials')??trim($_POST['photo_url']??$ex['photo']??'');
    $st=db()->prepare("UPDATE testimonials SET student_name=?,destination=?,university=?,review=?,photo=?,flag_emoji=?,avatar_color=?,rating=?,sort_order=?,status=? WHERE id=?");
    $st->bind_param('ssssssssiisi',$n,$d,$u,$r,$photo,$f,$c,$rating,$s,$status,$id);
    $st->execute();
    flash('Updated!','success');
    redirect(ADMIN_URL.'/pages/testimonials.php');
}

$items = db()->query("SELECT * FROM testimonials ORDER BY sort_order,id")->fetch_all(MYSQLI_ASSOC);
$editItem = isset($_GET['edit']) ? db()->query("SELECT * FROM testimonials WHERE id=".(int)$_GET['edit'])->fetch_assoc() : null;
?>
<div class="page-header">
    <h1>Testimonials</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 Testimonial</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['student_name'])?></h2>
        <a href="testimonials.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">Student Name *</label><input type="text" name="student_name" class="form-control" value="<?=e($editItem['student_name'])?>" required></div>
                <div class="form-group"><label class="form-label">Flag Emoji</label><input type="text" name="flag_emoji" class="form-control" value="<?=e($editItem['flag_emoji'])?>" placeholder="🇲🇹"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label class="form-label">Destination</label><input type="text" name="destination" class="form-control" value="<?=e($editItem['destination'])?>"></div>
                <div class="form-group"><label class="form-label">University</label><input type="text" name="university" class="form-control" value="<?=e($editItem['university'])?>"></div>
            </div>
            <div class="form-group"><label class="form-label">Review *</label><textarea name="review" class="form-control" rows="3" required><?=e($editItem['review'])?></textarea></div>
            <div class="form-row">
                <div class="form-group"><label class="form-label">Photo URL</label><input type="text" name="photo_url" class="form-control" value="<?=e($editItem['photo'])?>"></div>
                <div class="form-group"><label class="form-label">Avatar Color</label><div style="display:flex;gap:8px;align-items:center"><input type="color" name="avatar_color" value="<?=e($editItem['avatar_color']??'#1a56db')?>" style="width:50px;height:38px;border:1.5px solid var(--border);border-radius:8px;cursor:pointer"><span style="font-size:13px;color:var(--muted)">Used when no photo</span></div></div>
            </div>
            <div class="form-row-3">
                <div class="form-group"><label class="form-label">Rating</label><select name="rating" class="form-select"><option value="5" <?=$editItem['rating']==5?'selected':''?>>★★★★★</option><option value="4" <?=$editItem['rating']==4?'selected':''?>>★★★★☆</option><option value="3" <?=$editItem['rating']==3?'selected':''?>>★★★☆☆</option></select></div>
                <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 Changes</button>
        </form>
    </div>
</div>
<?php endif; ?>

<div class="card">
    <div class="card-header"><i class="fas fa-star" style="color:var(--accent)"></i><h2>All Testimonials</h2><span style="color:var(--muted);font-size:13px;margin-left:auto"><?=count($items)?> total</span></div>
    <div class="table-wrap">
        <?php if(empty($items)): ?>
        <div style="padding:40px;text-align:center;color:var(--muted)">No testimonials yet.</div>
        <?php else: ?>
        <table>
            <thead><tr><th>Student</th><th>Destination</th><th>Review</th><th>Rating</th><th>Status</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach($items as $t): ?>
            <tr>
                <td>
                    <div style="display:flex;align-items:center;gap:10px">
                        <?php if($t['photo']): ?>
                        <img src="<?=e(SITE_URL.'/'.$t['photo'])?>" style="width:36px;height:36px;border-radius:50%;object-fit:cover">
                        <?php else: ?>
                        <div style="width:36px;height:36px;border-radius:50%;background:<?=e($t['avatar_color']??'#1a56db')?>;display:flex;align-items:center;justify-content:center;color:#fff;font-weight:700;font-size:14px"><?=strtoupper(substr($t['student_name'],0,1))?></div>
                        <?php endif; ?>
                        <div><div style="font-weight:600"><?=e($t['student_name'])?></div><div style="font-size:11px;color:var(--muted)"><?=e($t['flag_emoji'])?> <?=e($t['destination'])?></div></div>
                    </div>
                </td>
                <td style="font-size:13px;color:var(--muted)"><?=e($t['university'])?></td>
                <td style="max-width:200px;font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?=e($t['review'])?></td>
                <td><?=str_repeat('★',(int)($t['rating']??5))?></td>
                <td><span class="badge <?=$t['status']==='active'?'badge-green':'badge-yellow'?>"><?=ucfirst($t['status'])?></span></td>
                <td>
                    <div style="display:flex;gap:5px">
                        <a href="?edit=<?=$t['id']?>" class="btn btn-secondary btn-sm btn-icon" title="Edit"><i class="fas fa-edit"></i></a>
                        <a href="?toggle=<?=$t['id']?>" class="btn btn-secondary btn-sm btn-icon" title="Toggle status"><i class="fas fa-toggle-<?=$t['status']==='active'?'on':'off'?>"></i></a>
                        <button onclick="confirmDelete('testimonials.php?delete=<?=$t['id']?>','<?=e(addslashes($t['student_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>

<!-- Add Modal -->
<div class="modal-overlay" id="addModal" onclick="if(event.target===this)this.classList.remove('open')" style="align-items:flex-start;padding:20px">
    <div class="modal-box" style="max-width:560px;max-height:90vh;overflow-y:auto">
        <div class="modal-title"><i class="fas fa-star" style="color:var(--accent)"></i> Add Testimonial</div>
        <form method="POST" enctype="multipart/form-data">
            <div class="form-row">
                <div class="form-group"><label class="form-label">Student Name *</label><input type="text" name="student_name" class="form-control" required placeholder="Rahim Uddin"></div>
                <div class="form-group"><label class="form-label">Flag Emoji</label><input type="text" name="flag_emoji" class="form-control" placeholder="🇲🇹"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label class="form-label">Destination</label><input type="text" name="destination" class="form-control" placeholder="Malta"></div>
                <div class="form-group"><label class="form-label">University</label><input type="text" name="university" class="form-control" placeholder="MCAST"></div>
            </div>
            <div class="form-group"><label class="form-label">Review *</label><textarea name="review" class="form-control" rows="3" required placeholder="CY Consultancy made my dream a reality..."></textarea></div>
            <div class="form-row">
                <div class="form-group"><label class="form-label">Photo Upload</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">Avatar Color</label><input type="color" name="avatar_color" value="#1a56db" style="width:100%;height:38px;border:1.5px solid var(--border);border-radius:8px;cursor:pointer"></div>
                <div class="form-group"><label class="form-label">Rating</label><select name="rating" class="form-select"><option value="5">★★★★★ (5)</option><option value="4">★★★★☆ (4)</option><option value="3">★★★☆☆ (3)</option></select></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'; ?>
