<?php
/**
 * Testimonials Management
 */

session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/security.php';
require_once __DIR__ . '/includes/auth.php';

checkAdminAuth();

$pdo = getDBConnection();
$message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'create';
    $id = intval($_POST['id'] ?? 0);
    
    $clientName = sanitizeInput($_POST['client_name'] ?? '');
    $clientPosition = sanitizeInput($_POST['client_position'] ?? '');
    $companyName = sanitizeInput($_POST['company_name'] ?? '');
    $testimonialText = sanitizeInput($_POST['testimonial_text'] ?? '');
    $rating = intval($_POST['rating'] ?? 5);
    $serviceType = sanitizeInput($_POST['service_type'] ?? '');
    $status = sanitizeInput($_POST['status'] ?? 'active');
    $featured = isset($_POST['featured']) ? 1 : 0;
    $displayOrder = intval($_POST['display_order'] ?? 0);
    
    // Handle image upload
    $clientPhoto = null;
    if (isset($_FILES['client_photo']) && $_FILES['client_photo']['error'] === UPLOAD_ERR_OK) {
        $allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
        if (in_array($_FILES['client_photo']['type'], $allowedTypes)) {
            $uploadDir = __DIR__ . '/../uploads/testimonials/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            $extension = pathinfo($_FILES['client_photo']['name'], PATHINFO_EXTENSION);
            $filename = uniqid() . '_' . time() . '.' . $extension;
            if (move_uploaded_file($_FILES['client_photo']['tmp_name'], $uploadDir . $filename)) {
                $clientPhoto = $filename;
            }
        }
    }
    
    if ($action === 'create') {
        $stmt = $pdo->prepare("
            INSERT INTO testimonials (client_name, client_position, company_name, testimonial_text, 
                                    rating, service_type, client_photo, status, featured, display_order)
            VALUES (:name, :position, :company, :text, :rating, :service, :photo, :status, :featured, :order)
        ");
        $stmt->execute([
            ':name' => $clientName,
            ':position' => $clientPosition,
            ':company' => $companyName,
            ':text' => $testimonialText,
            ':rating' => $rating,
            ':service' => $serviceType,
            ':photo' => $clientPhoto,
            ':status' => $status,
            ':featured' => $featured,
            ':order' => $displayOrder
        ]);
        $message = 'Testimonial created successfully!';
    } elseif ($action === 'update' && $id > 0) {
        if ($clientPhoto) {
            // Delete old photo if exists
            $old = $pdo->prepare("SELECT client_photo FROM testimonials WHERE id = :id");
            $old->execute([':id' => $id]);
            $oldPhoto = $old->fetchColumn();
            if ($oldPhoto) {
                $oldFile = __DIR__ . '/../uploads/testimonials/' . $oldPhoto;
                if (file_exists($oldFile)) unlink($oldFile);
            }
            $stmt = $pdo->prepare("
                UPDATE testimonials SET client_name = :name, client_position = :position, 
                company_name = :company, testimonial_text = :text, rating = :rating, 
                service_type = :service, client_photo = :photo, status = :status, 
                featured = :featured, display_order = :order WHERE id = :id
            ");
            $stmt->execute([
                ':name' => $clientName, ':position' => $clientPosition, ':company' => $companyName,
                ':text' => $testimonialText, ':rating' => $rating, ':service' => $serviceType,
                ':photo' => $clientPhoto, ':status' => $status, ':featured' => $featured,
                ':order' => $displayOrder, ':id' => $id
            ]);
        } else {
            $stmt = $pdo->prepare("
                UPDATE testimonials SET client_name = :name, client_position = :position, 
                company_name = :company, testimonial_text = :text, rating = :rating, 
                service_type = :service, status = :status, featured = :featured, 
                display_order = :order WHERE id = :id
            ");
            $stmt->execute([
                ':name' => $clientName, ':position' => $clientPosition, ':company' => $companyName,
                ':text' => $testimonialText, ':rating' => $rating, ':service' => $serviceType,
                ':status' => $status, ':featured' => $featured, ':order' => $displayOrder, ':id' => $id
            ]);
        }
        $message = 'Testimonial updated successfully!';
    }
}

// Handle delete
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $stmt = $pdo->prepare("SELECT client_photo FROM testimonials WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $photo = $stmt->fetchColumn();
    if ($photo) {
        $file = __DIR__ . '/../uploads/testimonials/' . $photo;
        if (file_exists($file)) unlink($file);
    }
    $pdo->prepare("DELETE FROM testimonials WHERE id = :id")->execute([':id' => $id]);
    $message = 'Testimonial deleted successfully!';
}

// Get edit item
$editItem = null;
if (isset($_GET['edit'])) {
    $id = intval($_GET['edit']);
    $stmt = $pdo->prepare("SELECT * FROM testimonials WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $editItem = $stmt->fetch();
}

// Get all testimonials
$testimonials = $pdo->query("
    SELECT * FROM testimonials ORDER BY display_order ASC, created_at DESC
")->fetchAll();

$pageTitle = 'Testimonials';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - Admin Panel</title>
    <link rel="stylesheet" href="assets/admin-modern.css">
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>
    
    <div class="admin-main">
        <?php include 'includes/header-new.php'; ?>
        
        <div class="admin-container">
            <?php if ($message): ?>
                <div class="message success"><?php echo htmlspecialchars($message); ?></div>
            <?php endif; ?>
            
            <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 1.5rem;">
                <!-- Form -->
                <div class="card slide-up">
                    <div class="card-header">
                        <h3 class="card-title"><?php echo $editItem ? 'Edit' : 'Add'; ?> Testimonial</h3>
                    </div>
                    <form method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="<?php echo $editItem ? 'update' : 'create'; ?>">
                        <?php if ($editItem): ?>
                            <input type="hidden" name="id" value="<?php echo $editItem['id']; ?>">
                        <?php endif; ?>
                        
                        <div class="form-group">
                            <label class="form-label">Client Name *</label>
                            <input type="text" name="client_name" class="form-control" 
                                   value="<?php echo htmlspecialchars($editItem['client_name'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Position</label>
                            <input type="text" name="client_position" class="form-control" 
                                   value="<?php echo htmlspecialchars($editItem['client_position'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Company Name</label>
                            <input type="text" name="company_name" class="form-control" 
                                   value="<?php echo htmlspecialchars($editItem['company_name'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Testimonial Text *</label>
                            <textarea name="testimonial_text" class="form-control" rows="4" required><?php echo htmlspecialchars($editItem['testimonial_text'] ?? ''); ?></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Rating</label>
                            <select name="rating" class="form-control">
                                <?php for ($i = 1; $i <= 5; $i++): ?>
                                    <option value="<?php echo $i; ?>" <?php echo ($editItem['rating'] ?? 5) == $i ? 'selected' : ''; ?>>
                                        <?php echo $i; ?> Star<?php echo $i > 1 ? 's' : ''; ?>
                                    </option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Service Type</label>
                            <select name="service_type" class="form-control">
                                <option value="">Select service</option>
                                <option value="survey" <?php echo ($editItem['service_type'] ?? '') === 'survey' ? 'selected' : ''; ?>>Hydrogeological Survey</option>
                                <option value="drilling" <?php echo ($editItem['service_type'] ?? '') === 'drilling' ? 'selected' : ''; ?>>Borehole Drilling</option>
                                <option value="solar-pump" <?php echo ($editItem['service_type'] ?? '') === 'solar-pump' ? 'selected' : ''; ?>>Solarized Pumps</option>
                                <option value="water-supply" <?php echo ($editItem['service_type'] ?? '') === 'water-supply' ? 'selected' : ''; ?>>Water Supply</option>
                                <option value="irrigation" <?php echo ($editItem['service_type'] ?? '') === 'irrigation' ? 'selected' : ''; ?>>Irrigation</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Client Photo</label>
                            <input type="file" name="client_photo" accept="image/*" class="form-control">
                            <?php if ($editItem && $editItem['client_photo']): ?>
                                <div style="margin-top: 0.5rem;">
                                    <img src="../uploads/testimonials/<?php echo htmlspecialchars($editItem['client_photo']); ?>" 
                                         style="width: 60px; height: 60px; object-fit: cover; border-radius: 8px;">
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Display Order</label>
                            <input type="number" name="display_order" class="form-control" 
                                   value="<?php echo $editItem['display_order'] ?? 0; ?>" min="0">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-control">
                                <option value="active" <?php echo ($editItem['status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Active</option>
                                <option value="inactive" <?php echo ($editItem['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>
                                <input type="checkbox" name="featured" value="1" 
                                       <?php echo ($editItem['featured'] ?? 0) ? 'checked' : ''; ?>> Featured
                            </label>
                        </div>
                        
                        <div style="display: flex; gap: 0.75rem;">
                            <button type="submit" class="btn btn-primary"><?php echo $editItem ? 'Update' : 'Create'; ?></button>
                            <?php if ($editItem): ?>
                                <a href="testimonials.php" class="btn btn-secondary">Cancel</a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
                
                <!-- List -->
                <div class="card slide-up" style="animation-delay: 0.2s">
                    <div class="card-header">
                        <h3 class="card-title">All Testimonials</h3>
                    </div>
                    <div style="max-height: 600px; overflow-y: auto;">
                        <?php if (empty($testimonials)): ?>
                            <p style="text-align: center; padding: 2rem; color: var(--text-secondary);">No testimonials yet</p>
                        <?php else: ?>
                            <?php foreach ($testimonials as $test): ?>
                            <div style="padding: 1rem; border-bottom: 1px solid var(--border-color);">
                                <div style="display: flex; gap: 1rem; align-items: start;">
                                    <?php if ($test['client_photo']): ?>
                                        <img src="../uploads/testimonials/<?php echo htmlspecialchars($test['client_photo']); ?>" 
                                             style="width: 60px; height: 60px; border-radius: 50%; object-fit: cover;">
                                    <?php else: ?>
                                        <div style="width: 60px; height: 60px; border-radius: 50%; background: var(--bg-primary); display: flex; align-items: center; justify-content: center; font-weight: 700; color: var(--text-secondary);">
                                            <?php echo strtoupper(substr($test['client_name'], 0, 1)); ?>
                                        </div>
                                    <?php endif; ?>
                                    <div style="flex: 1;">
                                        <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 0.5rem;">
                                            <div>
                                                <div style="font-weight: 600; color: var(--text-primary);"><?php echo htmlspecialchars($test['client_name']); ?></div>
                                                <?php if ($test['client_position']): ?>
                                                    <div style="font-size: 0.8125rem; color: var(--text-secondary);">
                                                        <?php echo htmlspecialchars($test['client_position']); ?>
                                                        <?php if ($test['company_name']): ?>
                                                            at <?php echo htmlspecialchars($test['company_name']); ?>
                                                        <?php endif; ?>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                            <div style="display: flex; gap: 0.5rem;">
                                                <?php if ($test['featured']): ?>
                                                    <span class="badge badge-warning">Featured</span>
                                                <?php endif; ?>
                                                <span class="badge badge-<?php echo $test['status'] === 'active' ? 'success' : 'danger'; ?>">
                                                    <?php echo ucfirst($test['status']); ?>
                                                </span>
                                            </div>
                                        </div>
                                        <div style="margin-bottom: 0.5rem;">
                                            <?php for ($i = 1; $i <= 5; $i++): ?>
                                                <span style="color: <?php echo $i <= $test['rating'] ? '#FBBF24' : '#E5E7EB'; ?>;">★</span>
                                            <?php endfor; ?>
                                        </div>
                                        <div style="font-size: 0.875rem; color: var(--text-secondary); font-style: italic; margin-bottom: 0.75rem;">
                                            "<?php echo htmlspecialchars(substr($test['testimonial_text'], 0, 150)); ?><?php echo strlen($test['testimonial_text']) > 150 ? '...' : ''; ?>"
                                        </div>
                                        <div style="display: flex; gap: 0.5rem;">
                                            <a href="?edit=<?php echo $test['id']; ?>" class="btn btn-sm btn-secondary">Edit</a>
                                            <a href="?delete=<?php echo $test['id']; ?>" 
                                               class="btn btn-sm btn-danger"
                                               onclick="return confirm('Delete this testimonial?')">Delete</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="assets/admin.js"></script>
</body>
</html>

