<?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.");
}

$error = '';
$success = '';
$upload_dir = 'uploads/testimonials/';

// Create upload directory if it doesn't exist
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// Handle testimonial creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_testimonial'])) {
    $student_name = trim($_POST['student_name'] ?? '');
    $program = trim($_POST['program'] ?? '');
    $country = trim($_POST['country'] ?? '');
    $testimonial_text = trim($_POST['testimonial_text'] ?? '');
    $rating = (int)($_POST['rating'] ?? 0);
    
    // Validate form data
    if (empty($student_name) || empty($testimonial_text) || $rating < 1 || $rating > 5) {
        $error = "Student name, testimonial text, and valid rating (1-5) are required.";
    } else {
        try {
            // Handle student photo upload
            $photo_path = null;
            if (isset($_FILES['student_photo']) && $_FILES['student_photo']['error'] === UPLOAD_ERR_OK) {
                $file_name = $_FILES['student_photo']['name'];
                $file_tmp = $_FILES['student_photo']['tmp_name'];
                $file_size = $_FILES['student_photo']['size'];
                $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                
                $allowed_exts = ['jpg', 'jpeg', 'png', 'gif'];
                $max_size = 2 * 1024 * 1024; // 2MB
                
                if (in_array($file_ext, $allowed_exts) && $file_size <= $max_size) {
                    $unique_name = 'testimonial_' . time() . '_' . rand(1000, 9999) . '.' . $file_ext;
                    $file_path = $upload_dir . $unique_name;
                    
                    if (move_uploaded_file($file_tmp, $file_path)) {
                        $photo_path = $file_path;
                    }
                } else {
                    throw new Exception("Invalid file type or size for student photo.");
                }
            }
            
            // Insert testimonial
            $stmt = $pdo->prepare("INSERT INTO testimonials (
                student_name, program, country, testimonial_text, rating, student_photo, status, created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, 'approved', NOW(), NOW())");
            
            $stmt->execute([
                $student_name, $program, $country, $testimonial_text, $rating, $photo_path
            ]);
            
            $testimonial_id = $pdo->lastInsertId();
            
            // Log the activity
            $pdo->prepare("INSERT INTO activities (
                user_id, activity_type, description, created_at
            ) VALUES (?, ?, ?, NOW())")->execute([
                $_SESSION['user_id'],
                "testimonial_created",
                "Admin {$admin['first_name']} {$admin['last_name']} created testimonial for {$student_name}"
            ]);
            
            $success = "Testimonial created successfully!";
            header('Location: admin-testimonials.php?success=created');
            exit;
            
        } catch (Exception $e) {
            $error = "Failed to create testimonial. Please try again.";
        }
    }
}

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Create Testimonial - 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>
        .form-section {
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }
        .section-title {
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #3fb7fe;
        }
        .file-upload {
            position: relative;
            border: 2px dashed #dee2e6;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        .file-upload:hover {
            border-color: #3fb7fe;
            background: #f8f9fa;
        }
        .file-input {
            display: none;
        }
        .preview-image {
            max-width: 100%;
            max-height: 150px;
            margin-top: 10px;
            border-radius: 5px;
            display: none;
        }
        .upload-info {
            margin-top: 10px;
            font-size: 0.8em;
            color: #666;
        }
        .rating-stars {
            font-size: 2em;
            color: #ccc;
            cursor: pointer;
        }
        .rating-stars i {
            margin: 0 2px;
        }
        .rating-stars i:hover,
        .rating-stars i:hover ~ i {
            color: #ffc107 !important;
        }
        .filled {
            color: #ffc107 !important;
        }
    </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">Create New Testimonial</h1>
        </div>
        
        <?php if ($error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        
        <?php if ($success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
        <?php endif; ?>
        
        <form method="POST" enctype="multipart/form-data">
            <!-- Student Information -->
            <div class="form-section">
                <h5 class="section-title">Student Information</h5>
                <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>
                        <div class="rating-stars" id="ratingStars">
                            <i class="far fa-star" data-value="1"></i>
                            <i class="far fa-star" data-value="2"></i>
                            <i class="far fa-star" data-value="3"></i>
                            <i class="far fa-star" data-value="4"></i>
                            <i class="far fa-star" data-value="5"></i>
                        </div>
                        <input type="hidden" name="rating" id="ratingValue" required>
                        <small class="form-text text-muted">Click on the stars to rate (1-5)</small>
                    </div>
                </div>
            </div>
            
            <!-- Testimonial Content -->
            <div class="form-section">
                <h5 class="section-title">Testimonial Content</h5>
                <div class="form-group">
                    <label>Testimonial Text *</label>
                    <textarea name="testimonial_text" class="form-control" rows="6" required placeholder="Enter the student's testimonial..."></textarea>
                </div>
            </div>
            
            <!-- Student Photo -->
            <div class="form-section">
                <h5 class="section-title">Student Photo</h5>
                <div class="form-group">
                    <label>Upload Student Photo</label>
                    <div class="file-upload" id="photoUpload">
                        <i class="fas fa-file-upload fa-3x mb-3" style="color: #3fb7fe;"></i>
                        <h6>Upload Photo</h6>
                        <p class="text-muted small">JPG, PNG, GIF (max 2MB)</p>
                        <img id="photoPreview" class="preview-image" alt="Photo preview">
                        <input type="file" name="student_photo" id="photoFile" class="file-input" accept="image/*">
                        <div class="upload-info" id="photoInfo"></div>
                    </div>
                </div>
            </div>
            
            <!-- Form Submission -->
            <div class="text-center">
                <button type="submit" name="create_testimonial" class="btn btn-primary btn-lg px-5">Create Testimonial</button>
                <a href="admin-testimonials.php" class="btn btn-outline-secondary ml-2">Cancel</a>
            </div>
        </form>
    </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>
        // Photo upload functionality
        document.getElementById('photoUpload').addEventListener('click', function() {
            document.getElementById('photoFile').click();
        });
        
        document.getElementById('photoFile').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                // Display file info
                document.getElementById('photoInfo').innerHTML = `
                    <strong>File:</strong> ${file.name} <br>
                    <strong>Size:</strong> ${(file.size / 1024 / 1024).toFixed(2)} MB <br>
                    <strong>Type:</strong> ${file.type}
                `;
                
                // Show image preview if it's an image
                if (file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        document.getElementById('photoPreview').src = e.target.result;
                        document.getElementById('photoPreview').style.display = 'block';
                        document.getElementById('photoUpload').querySelectorAll('i, h6, p').forEach(el => {
                            el.style.display = 'none';
                        });
                    };
                    reader.readAsDataURL(file);
                }
            }
        });
        
        // Rating stars functionality
        const stars = document.querySelectorAll('.rating-stars i');
        const ratingValue = document.getElementById('ratingValue');
        
        stars.forEach(star => {
            star.addEventListener('click', function() {
                const value = this.getAttribute('data-value');
                ratingValue.value = value;
                
                // Update star appearance
                stars.forEach(s => {
                    if (s.getAttribute('data-value') <= value) {
                        s.classList.remove('far');
                        s.classList.add('fas', 'filled');
                    } else {
                        s.classList.remove('fas', 'filled');
                        s.classList.add('far');
                    }
                });
            });
            
            star.addEventListener('mouseover', function() {
                const value = this.getAttribute('data-value');
                
                stars.forEach(s => {
                    if (s.getAttribute('data-value') <= value) {
                        s.classList.add('hover');
                    } else {
                        s.classList.remove('hover');
                    }
                });
            });
            
            star.addEventListener('mouseout', function() {
                stars.forEach(s => {
                    s.classList.remove('hover');
                });
            });
        });
    </script>
</body>
</html>