<?php
/**
 * Admin Testimonials - FIXED VERSION
 * Digital Product Store
 */

require_once __DIR__ . '/includes/header.php';

$page_title = 'Testimonials';

// Handle actions
if (isset($_GET['action']) && isset($_GET['id'])) {
    $testimonial_id = (int)$_GET['id'];
    $action = sanitize($_GET['action']);
    
    switch ($action) {
        case 'delete':
            try {
                $stmt = $pdo->prepare("DELETE FROM testimonials WHERE id = ?");
                $stmt->execute([$testimonial_id]);
                set_flash_message('success', 'Testimonial deleted successfully.');
            } catch (PDOException $e) {
                set_flash_message('error', 'Failed to delete testimonial: ' . $e->getMessage());
            }
            header('Location: ' . ADMIN_URL . '/testimonials.php');
            exit;
            
        case 'toggle':
            try {
                $stmt = $pdo->prepare("UPDATE testimonials SET is_active = NOT is_active WHERE id = ?");
                $stmt->execute([$testimonial_id]);
                set_flash_message('success', 'Testimonial status updated.');
            } catch (PDOException $e) {
                set_flash_message('error', 'Failed to update status.');
            }
            header('Location: ' . ADMIN_URL . '/testimonials.php');
            exit;
    }
}

// Handle add/edit testimonial
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $testimonial_id = isset($_POST['testimonial_id']) ? (int)$_POST['testimonial_id'] : 0;
    $name = sanitize($_POST['name'] ?? '');
    $title = sanitize($_POST['title'] ?? '');
    $content = sanitize($_POST['content'] ?? '');
    $rating = (int)($_POST['rating'] ?? 5);
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    
    // Handle image upload
    $image = null;
    if (!empty($_FILES['image']['name'])) {
        $upload_result = upload_image($_FILES['image'], 'testimonials');
        if ($upload_result['success']) {
            $image = $upload_result['path'];
        } else {
            set_flash_message('error', 'Image upload failed: ' . $upload_result['message']);
        }
    }
    
    if (empty($name)) {
        set_flash_message('error', 'Customer name is required.');
    } elseif (empty($content)) {
        set_flash_message('error', 'Testimonial content is required.');
    } else {
        try {
            if ($testimonial_id > 0) {
                // Update existing testimonial
                $sql = "UPDATE testimonials SET 
                    name = ?, title = ?, content = ?, rating = ?, 
                    sort_order = ?, is_active = ?";
                $params = [$name, $title, $content, $rating, $sort_order, $is_active];
                
                if ($image) {
                    $sql .= ", image = ?";
                    $params[] = $image;
                }
                
                $sql .= " WHERE id = ?";
                $params[] = $testimonial_id;
                
                $stmt = $pdo->prepare($sql);
                $stmt->execute($params);
                set_flash_message('success', 'Testimonial updated successfully.');
            } else {
                // Add new testimonial
                $stmt = $pdo->prepare("INSERT INTO testimonials 
                    (name, title, content, image, rating, sort_order, is_active, created_at) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
                $stmt->execute([
                    $name, $title, $content, $image, $rating, $sort_order, $is_active
                ]);
                set_flash_message('success', 'Testimonial created successfully.');
            }
        } catch (PDOException $e) {
            set_flash_message('error', 'Database error: ' . $e->getMessage());
        }
    }
    
    header('Location: ' . ADMIN_URL . '/testimonials.php');
    exit;
}

// Get all testimonials
try {
    $stmt = $pdo->query("SELECT * FROM testimonials ORDER BY sort_order, created_at DESC");
    $testimonials = $stmt->fetchAll();
} catch (PDOException $e) {
    $testimonials = [];
}

// Get testimonial to edit
$edit_testimonial = null;
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    try {
        $stmt = $pdo->prepare("SELECT * FROM testimonials WHERE id = ?");
        $stmt->execute([$edit_id]);
        $edit_testimonial = $stmt->fetch();
    } catch (PDOException $e) {
        // Silently fail
    }
}
?>

<div class="page-header">
    <div>
        <h1>Testimonials</h1>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="<?php echo ADMIN_URL; ?>/index.php">Dashboard</a></li>
                <li class="breadcrumb-item active">Testimonials</li>
            </ol>
        </nav>
    </div>
</div>

<?php echo get_flash_message(); ?>

<div class="row">
    <!-- Add/Edit Form -->
    <div class="col-lg-4">
        <div class="card">
            <div class="card-header">
                <?php echo $edit_testimonial ? 'Edit Testimonial' : 'Add New Testimonial'; ?>
            </div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <?php if ($edit_testimonial): ?>
                    <input type="hidden" name="testimonial_id" value="<?php echo $edit_testimonial['id']; ?>">
                    <?php endif; ?>
                    
                    <div class="mb-3">
                        <label class="form-label">Customer Name *</label>
                        <input type="text" name="name" class="form-control" 
                               value="<?php echo htmlspecialchars($edit_testimonial['name'] ?? ''); ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Title/Position</label>
                        <input type="text" name="title" class="form-control" 
                               value="<?php echo htmlspecialchars($edit_testimonial['title'] ?? ''); ?>">
                        <small class="text-muted">e.g., "CEO, Company Name" or "Verified Buyer"</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Testimonial Content *</label>
                        <textarea name="content" class="form-control" rows="4" required><?php echo htmlspecialchars($edit_testimonial['content'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Customer Photo</label>
                        <input type="file" name="image" class="form-control" accept="image/*">
                        <?php if (!empty($edit_testimonial['image'])): ?>
                        <div class="mt-2">
                            <img src="<?php echo BASE_URL . '/' . $edit_testimonial['image']; ?>" alt="" class="img-thumbnail" style="max-height: 100px;">
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Rating</label>
                        <select name="rating" class="form-select">
                            <option value="5" <?php echo ($edit_testimonial['rating'] ?? 5) == 5 ? 'selected' : ''; ?>>5 Stars - Excellent</option>
                            <option value="4" <?php echo ($edit_testimonial['rating'] ?? 5) == 4 ? 'selected' : ''; ?>>4 Stars - Very Good</option>
                            <option value="3" <?php echo ($edit_testimonial['rating'] ?? 5) == 3 ? 'selected' : ''; ?>>3 Stars - Good</option>
                            <option value="2" <?php echo ($edit_testimonial['rating'] ?? 5) == 2 ? 'selected' : ''; ?>>2 Stars - Fair</option>
                            <option value="1" <?php echo ($edit_testimonial['rating'] ?? 5) == 1 ? 'selected' : ''; ?>>1 Star - Poor</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Sort Order</label>
                        <input type="number" name="sort_order" class="form-control" 
                               value="<?php echo $edit_testimonial['sort_order'] ?? 0; ?>">
                        <small class="text-muted">Lower numbers appear first</small>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input type="checkbox" name="is_active" class="form-check-input" id="is_active" 
                                   <?php echo ($edit_testimonial['is_active'] ?? 1) ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="is_active">Active</label>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-save"></i> <?php echo $edit_testimonial ? 'Update Testimonial' : 'Add Testimonial'; ?>
                    </button>
                    
                    <?php if ($edit_testimonial): ?>
                    <a href="<?php echo ADMIN_URL; ?>/testimonials.php" class="btn btn-outline-secondary w-100 mt-2">
                        <i class="fas fa-times"></i> Cancel
                    </a>
                    <?php endif; ?>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Testimonials List -->
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span>All Testimonials</span>
                <span class="text-muted"><?php echo count($testimonials); ?> testimonials</span>
            </div>
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Customer</th>
                            <th>Title</th>
                            <th>Rating</th>
                            <th>Content</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($testimonials)): ?>
                        <tr>
                            <td colspan="6" class="text-center py-4">
                                <i class="fas fa-comment fa-3x text-muted mb-3"></i>
                                <p>No testimonials found.</p>
                            </td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($testimonials as $testimonial): ?>
                        <tr>
                            <td>
                                <div class="d-flex align-items-center">
                                    <?php if (!empty($testimonial['image'])): ?>
                                    <img src="<?php echo BASE_URL . '/' . $testimonial['image']; ?>" alt="" class="rounded-circle me-2" style="width: 40px; height: 40px; object-fit: cover;">
                                    <?php else: ?>
                                    <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 40px; height: 40px;">
                                        <?php echo strtoupper(substr($testimonial['name'], 0, 1)); ?>
                                    </div>
                                    <?php endif; ?>
                                    <div class="fw-bold"><?php echo htmlspecialchars($testimonial['name']); ?></div>
                                </div>
                            </td>
                            <td><?php echo htmlspecialchars($testimonial['title'] ?? ''); ?></td>
                            <td>
                                <?php for ($i = 1; $i <= 5; $i++): ?>
                                <i class="fas fa-star<?php echo $i <= ($testimonial['rating'] ?? 5) ? ' text-warning' : ' text-muted'; ?>"></i>
                                <?php endfor; ?>
                            </td>
                            <td><?php echo htmlspecialchars(truncate($testimonial['content'], 50)); ?></td>
                            <td>
                                <?php if (($testimonial['is_active'] ?? 1)): ?>
                                <span class="badge bg-success">Active</span>
                                <?php else: ?>
                                <span class="badge bg-secondary">Inactive</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="btn-group">
                                    <a href="?edit=<?php echo $testimonial['id']; ?>" class="btn btn-sm btn-info" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="?action=toggle&id=<?php echo $testimonial['id']; ?>" class="btn btn-sm btn-warning" title="Toggle Status">
                                        <i class="fas fa-power-off"></i>
                                    </a>
                                    <a href="?action=delete&id=<?php echo $testimonial['id']; ?>" class="btn btn-sm btn-danger" title="Delete" onclick="return confirm('Are you sure?')">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
