<?php
require_once __DIR__ . '/config.php';
requireAdmin();
$pdo = getDB();
$feedbackDir = dirname(__DIR__) . '/uploads/feedback/';
if (!is_dir($feedbackDir)) @mkdir($feedbackDir, 0755, true);

function handleUpload($fileKey, $dir, $prefix = 'fb') {
    if (empty($_FILES[$fileKey]['name'])) return null;
    $ext = strtolower(pathinfo($_FILES[$fileKey]['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, ['jpg','jpeg','png','gif','webp'])) return null;
    $fname = $prefix . '_' . time() . '.' . $ext;
    if (move_uploaded_file($_FILES[$fileKey]['tmp_name'], $dir . $fname)) return $fname;
    return null;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_POST['delete_id'])) {
        try {
            $id = (int)$_POST['delete_id'];
            $stmt = $pdo->prepare("SELECT image FROM client_feedback WHERE id = ?");
            $stmt->execute([$id]);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($row && !empty($row['image']) && is_file($feedbackDir . $row['image'])) @unlink($feedbackDir . $row['image']);
            $pdo->prepare("DELETE FROM client_feedback WHERE id = ?")->execute([$id]);
        } catch (Exception $e) { /* */ }
        header('Location: client-feedback.php');
        exit;
    }
    if (!empty($_POST['save_settings'])) {
        $title = trim($_POST['client_feedback_title'] ?? '');
        $pdo->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES ('client_feedback_title', ?) ON DUPLICATE KEY UPDATE setting_value = ?")->execute([$title, $title]);
        header('Location: client-feedback.php?saved=1');
        exit;
    }
    if (!empty($_POST['add_feedback'])) {
        try {
            $name = trim($_POST['customer_name'] ?? '');
            $designation = trim($_POST['designation'] ?? '');
            $message = trim($_POST['message'] ?? '');
            $sort = (int)($_POST['sort_order'] ?? 0);
            $img = handleUpload('image', $feedbackDir, 'fb');
            if ($name && $message) {
                $pdo->prepare("INSERT INTO client_feedback (customer_name, designation, message, image, sort_order) VALUES (?,?,?,?,?)")->execute([$name, $designation ?: null, $message, $img, $sort]);
            }
        } catch (Exception $e) { /* */ }
        header('Location: client-feedback.php');
        exit;
    }
    if (!empty($_POST['edit_id'])) {
        try {
            $id = (int)$_POST['edit_id'];
            $name = trim($_POST['customer_name'] ?? '');
            $designation = trim($_POST['designation'] ?? '');
            $message = trim($_POST['message'] ?? '');
            $sort = (int)($_POST['sort_order'] ?? 0);
            $active = isset($_POST['is_active']) ? 1 : 0;
            $img = handleUpload('image', $feedbackDir, 'fb');
            $stmt = $pdo->prepare("SELECT image FROM client_feedback WHERE id = ?");
            $stmt->execute([$id]);
            $old = $stmt->fetch(PDO::FETCH_ASSOC);
            $image = $img ?: ($old['image'] ?? null);
            if ($img && $old && !empty($old['image']) && is_file($feedbackDir . $old['image'])) @unlink($feedbackDir . $old['image']);
            $pdo->prepare("UPDATE client_feedback SET customer_name=?, designation=?, message=?, image=?, sort_order=?, is_active=? WHERE id=?")->execute([$name, $designation ?: null, $message, $image, $sort, $active, $id]);
        } catch (Exception $e) { /* */ }
        header('Location: client-feedback.php');
        exit;
    }
}

$list = [];
try {
    $list = $pdo->query("SELECT * FROM client_feedback ORDER BY sort_order, id")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { /* */ }
$feedbackTitle = getSetting('client_feedback_title', 'What Our Clients Say');
$pageTitle = 'Client Feedback';
require_once __DIR__ . '/includes/header.php';
?>
<div class="admin-page">
    <h1>Client Feedback <small style="font-weight:400;color:#666">(testimonials on Client &amp; Feedback page)</small></h1>
    <?php if (isset($_GET['saved'])): ?><p class="success">Saved.</p><?php endif; ?>
    <p><a href="<?php echo ADMIN_SITE_ROOT; ?>/clients-feedback.php" target="_blank" class="btn btn-secondary">View Client &amp; Feedback page</a></p>
    <p class="muted">Client logos are managed in <a href="clients.php">Our clients</a>. This page manages testimonials (what clients say).</p>

    <h2>Section heading</h2>
    <form method="post" class="admin-form" style="max-width:520px;">
        <input type="hidden" name="save_settings" value="1">
        <label>Feedback section title</label>
        <input type="text" name="client_feedback_title" value="<?php echo htmlspecialchars($feedbackTitle); ?>" placeholder="What Our Clients Say">
        <button type="submit" class="btn">Save</button>
    </form>

    <h2 style="margin-top:2rem;">Add testimonial</h2>
    <form method="post" enctype="multipart/form-data" class="admin-form" style="max-width:560px;">
        <input type="hidden" name="add_feedback" value="1">
        <label>Customer / client name *</label>
        <input type="text" name="customer_name" required placeholder="John Smith">
        <label>Designation (optional)</label>
        <input type="text" name="designation" placeholder="Procurement Manager, ABC Ltd">
        <label>Message / description *</label>
        <textarea name="message" rows="4" required placeholder="What the client said..."></textarea>
        <label>Customer image (optional)</label>
        <input type="file" name="image" accept="image/*">
        <label>Sort order</label>
        <input type="number" name="sort_order" value="0">
        <button type="submit" class="btn">Add testimonial</button>
    </form>

    <h2 style="margin-top:2rem;">Testimonials list</h2>
    <table class="admin-table">
        <thead><tr><th>Photo</th><th>Name</th><th>Designation</th><th>Message</th><th>Order</th><th>Active</th><th>Actions</th></tr></thead>
        <tbody>
            <?php foreach ($list as $f): ?>
            <tr>
                <td>
                    <?php if (!empty($f['image']) && is_file($feedbackDir . $f['image'])): ?>
                    <img src="<?php echo ADMIN_SITE_ROOT; ?>/uploads/feedback/<?php echo htmlspecialchars($f['image']); ?>" alt="" style="max-height:44px; border-radius:50%;">
                    <?php else: ?>—<?php endif; ?>
                </td>
                <td><?php echo htmlspecialchars($f['customer_name']); ?></td>
                <td><?php echo htmlspecialchars(mb_substr($f['designation'] ?? '', 0, 30)); ?><?php echo mb_strlen($f['designation'] ?? '') > 30 ? '…' : ''; ?></td>
                <td><?php echo htmlspecialchars(mb_substr($f['message'], 0, 50)); ?>…</td>
                <td><?php echo (int)$f['sort_order']; ?></td>
                <td><?php echo $f['is_active'] ? 'Yes' : 'No'; ?></td>
                <td>
                    <form method="post" style="display:inline;" onsubmit="return confirm('Delete this testimonial?');">
                        <input type="hidden" name="delete_id" value="<?php echo (int)$f['id']; ?>">
                        <button type="submit" class="link-btn">Delete</button>
                    </form>
                </td>
            </tr>
            <tr><td colspan="7">
                <form method="post" enctype="multipart/form-data" class="admin-form" style="padding:12px; background:#f8fafc; border-radius:8px;">
                    <input type="hidden" name="edit_id" value="<?php echo (int)$f['id']; ?>">
                    <input type="text" name="customer_name" value="<?php echo htmlspecialchars($f['customer_name']); ?>" placeholder="Name" required style="width:160px;">
                    <input type="text" name="designation" value="<?php echo htmlspecialchars($f['designation'] ?? ''); ?>" placeholder="Designation" style="width:200px;">
                    <textarea name="message" rows="2" required style="width:100%; max-width:400px;"><?php echo htmlspecialchars($f['message']); ?></textarea>
                    <input type="number" name="sort_order" value="<?php echo (int)$f['sort_order']; ?>" style="width:60px;">
                    <label><input type="checkbox" name="is_active" value="1" <?php echo $f['is_active'] ? 'checked' : ''; ?>> Active</label>
                    <input type="file" name="image" accept="image/*" title="Customer photo">
                    <button type="submit" class="btn">Save</button>
                </form>
            </td></tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php if (empty($list)): ?>
    <p class="muted">No testimonials yet. Run <code>database/client_feedback_menu.sql</code> to create the table and seed data, or add above.</p>
    <?php endif; ?>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
