<?php
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
    header('Location: admin-login.php');
    exit;
}

// Get admin data
$stmt = $pdo->prepare("SELECT a.*, u.email FROM admins a JOIN users u ON a.id = u.id WHERE a.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin) {
    die("Admin profile not found.");
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_testimonial'])) {
    $student_name = trim($_POST['student_name'] ?? '');
    $program = trim($_POST['program'] ?? '');
    $country = trim($_POST['country'] ?? '');
    $rating = $_POST['rating'] ?? 5;
    $content = $_POST['content'] ?? '';
    $is_featured = isset($_POST['is_featured']) ? 1 : 0;
    
    if ($student_name && $content) {
        try {
            $stmt = $pdo->prepare("INSERT INTO testimonials (
                student_name, program, country, rating, content, is_featured, created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())");
            
            $stmt->execute([$student_name, $program, $country, $rating, $content, $is_featured]);
            
            $success = "Testimonial added successfully!";
            
        } catch (Exception $e) {
            $error = "Failed to add testimonial. Please try again.";
        }
    } else {
        $error = "Please fill in all required fields.";
    }
}

// Get testimonials
$featured_filter = isset($_GET['featured']) ? (int)$_GET['featured'] : null;
$search = $_GET['search'] ?? '';

$sql = "SELECT * FROM testimonials";
$conditions = [];
$params = [];

if ($featured_filter !== null) {
    $conditions[] = "is_featured = ?";
    $params[] = $featured_filter;
}

if ($search) {
    $conditions[] = "(student_name LIKE ? OR program LIKE ? OR country LIKE ? OR content LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($conditions) {
    $sql .= " WHERE " . implode(" AND ", $conditions);
}

$sql .= " ORDER BY is_featured DESC, created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$testimonials = $stmt->fetchAll();

// Get stats
$stats = [
    'total' => $pdo->query("SELECT COUNT(*) FROM testimonials")->fetchColumn(),
    'featured' => $pdo->query("SELECT COUNT(*) FROM testimonials WHERE is_featured = 1")->fetchColumn(),
];

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Testimonials - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .stat-card {
            border-left: 5px solid #3fb7fe;
            margin-bottom: 20px;
        }
        .rating {
            color: #ffc107;
        }
        .featured-badge {
            font-size: 0.8em;
            padding: 3px 8px;
            border-radius: 15px;
        }
        .featured-yes {
            background: #d1ecf1;
            color: #0c5460;
        }
        .featured-no {
            background: #f8f9fa;
            color: #6c757d;
        }
    </style>
</head>
<body>

<?php include 'admin-navbar.php'; ?>

<div class="container py-5">
    <div class="section-title position-relative mb-4">
        <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Content Management</h6>
        <h1 class="display-5">Manage Student Testimonials</h1>
    </div>

    <?php if (isset($error)): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    
    <?php if (isset($success)): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <!-- Add Testimonial Form -->
    <div class="bg-white p-4 rounded mb-4">
        <h5 class="mb-3">Add New Testimonial</h5>
        <form method="POST">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Student Name *</label>
                    <input type="text" name="student_name" class="form-control" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label>Program</label>
                    <input type="text" name="program" class="form-control">
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Country</label>
                    <input type="text" name="country" class="form-control">
                </div>
                <div class="col-md-6 mb-3">
                    <label>Rating *</label>
                    <select name="rating" class="form-control" required>
                        <option value="5">5 Stars</option>
                        <option value="4">4 Stars</option>
                        <option value="3">3 Stars</option>
                        <option value="2">2 Stars</option>
                        <option value="1">1 Star</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label>Testimonial *</label>
                <textarea name="content" class="form-control" rows="4" required></textarea>
            </div>
            <div class="form-group">
                <div class="custom-control custom-checkbox">
                    <input type="checkbox" class="custom-control-input" id="is_featured" name="is_featured">
                    <label class="custom-control-label" for="is_featured">Feature on Homepage</label>
                </div>
            </div>
            <button type="submit" name="add_testimonial" class="btn btn-primary">Add Testimonial</button>
        </form>
    </div>

    <!-- Search and Filter -->
    <div class="row mb-4">
        <div class="col-lg-8">
            <form method="GET" class="d-flex">
                <div class="flex-grow-1 mr-2">
                    <input type="text" name="search" class="form-control" placeholder="Search by name, program, or content" 
                           value="<?= htmlspecialchars($search) ?>">
                </div>
                <button type="submit" class="btn btn-primary">Search</button>
            </form>
        </div>
        <div class="col-lg-4">
            <select name="featured" class="form-control" onchange="window.location='admin-testimonials.php?featured='+this.value<?= $search ? '&search='.urlencode($search) : '' ?>">
                <option value="">All Testimonials</option>
                <option value="1" <?= $featured_filter === 1 ? 'selected' : '' ?>>Featured Only</option>
                <option value="0" <?= $featured_filter === 0 ? 'selected' : '' ?>>Non-Featured Only</option>
            </select>
        </div>
    </div>

    <!-- Stats -->
    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="stat-card">
                <div class="card-body">
                    <h6>Total Testimonials</h6>
                    <h3><?= $stats['total'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="stat-card" style="border-left-color: #0c5460;">
                <div class="card-body">
                    <h6>Featured</h6>
                    <h3><?= $stats['featured'] ?></h3>
                </div>
            </div>
        </div>
    </div>

    <!-- Testimonials List -->
    <div class="row">
        <?php foreach ($testimonials as $testimonial): ?>
        <div class="col-md-6 mb-4">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex justify-content-between mb-2">
                        <h6 class="mb-0"><?= htmlspecialchars($testimonial['student_name']) ?></h6>
                        <div class="rating">
                            <?php for ($i = 1; $i <= 5; $i++): ?>
                                <i class="fas <?= $i <= $testimonial['rating'] ? 'fa-star' : 'fa-star-half-alt' ?>"></i>
                            <?php endfor; ?>
                        </div>
                    </div>
                    <?php if ($testimonial['program'] || $testimonial['country']): ?>
                    <div class="text-muted mb-2">
                        <?php if ($testimonial['program']): ?>
                            <small><?= htmlspecialchars($testimonial['program']) ?></small>
                        <?php endif; ?>
                        <?php if ($testimonial['country']): ?>
                            <?php if ($testimonial['program']): ?> | <?php endif; ?>
                            <small><?= htmlspecialchars($testimonial['country']) ?></small>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                    <p class="mb-3">"<?= htmlspecialchars($testimonial['content']) ?>"</p>
                    <div class="d-flex justify-content-between align-items-center">
                        <span class="featured-badge featured-<?= $testimonial['is_featured'] ? 'yes' : 'no' ?>">
                            <?= $testimonial['is_featured'] ? 'Featured' : 'Standard' ?>
                        </span>
                        <div>
                            <button class="btn btn-sm btn-outline-primary edit-testimonial" data-id="<?= $testimonial['id'] ?>">Edit</button>
                            <button class="btn btn-sm btn-danger delete-testimonial" data-id="<?= $testimonial['id'] ?>">Delete</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<?php include 'footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<script>
    $('.edit-testimonial').on('click', function() {
        const testimonialId = $(this).data('id');
        alert('In a real application, this would open an edit form for the testimonial.');
    });
    
    $('.delete-testimonial').on('click', function() {
        const testimonialId = $(this).data('id');
        if (confirm('Are you sure you want to delete this testimonial? This action cannot be undone.')) {
            alert('In a real application, this would delete the testimonial from the database.');
        }
    });
</script>
</body>
</html>