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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_POST['delete_id'])) {
        $id = (int)$_POST['delete_id'];
        $stmt = $pdo->prepare("SELECT logo FROM our_clients WHERE id = ?");
        $stmt->execute([$id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row && !empty($row['logo']) && is_file($clientsDir . $row['logo'])) {
            @unlink($clientsDir . $row['logo']);
        }
        $pdo->prepare("DELETE FROM our_clients WHERE id = ?")->execute([$id]);
        header('Location: clients.php');
        exit;
    }
    if (isset($_POST['save_settings'])) {
        $pdo->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES ('our_clients_title', ?) ON DUPLICATE KEY UPDATE setting_value = ?")->execute([trim($_POST['our_clients_title'] ?? ''), trim($_POST['our_clients_title'] ?? '')]);
        $pdo->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES ('our_clients_subtext', ?) ON DUPLICATE KEY UPDATE setting_value = ?")->execute([trim($_POST['our_clients_subtext'] ?? ''), trim($_POST['our_clients_subtext'] ?? '')]);
        header('Location: clients.php?saved=1');
        exit;
    }
    if (!empty($_POST['add_client']) && !empty($_FILES['logo']['name'])) {
        $name = trim($_POST['name'] ?? '');
        $url = trim($_POST['website_url'] ?? '');
        $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
        if ($name && in_array($ext, ['jpg','jpeg','png','gif','webp','svg'])) {
            $fname = 'client_' . time() . '_' . preg_replace('/[^a-z0-9]/i', '', $name) . '.' . $ext;
            $fname = substr($fname, 0, 120);
            if (move_uploaded_file($_FILES['logo']['tmp_name'], $clientsDir . $fname)) {
                $pdo->prepare("INSERT INTO our_clients (name, logo, website_url, sort_order) VALUES (?, ?, ?, ?)")->execute([
                    $name, $fname, $url ?: null, (int)($_POST['sort_order'] ?? 0)
                ]);
            }
        }
        header('Location: clients.php');
        exit;
    }
    if (!empty($_POST['edit_id'])) {
        $id = (int)$_POST['edit_id'];
        $name = trim($_POST['name'] ?? '');
        $url = trim($_POST['website_url'] ?? '');
        $sort = (int)($_POST['sort_order'] ?? 0);
        $active = isset($_POST['is_active']) ? 1 : 0;
        $pdo->prepare("UPDATE our_clients SET name=?, website_url=?, sort_order=?, is_active=? WHERE id=?")->execute([
            $name, $url ?: null, $sort, $active, $id
        ]);
        if (!empty($_FILES['logo']['name'])) {
            $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg','jpeg','png','gif','webp','svg'])) {
                $stmt = $pdo->prepare("SELECT logo FROM our_clients WHERE id = ?");
                $stmt->execute([$id]);
                $old = $stmt->fetchColumn();
                $fname = 'client_' . $id . '_' . time() . '.' . $ext;
                if (move_uploaded_file($_FILES['logo']['tmp_name'], $clientsDir . $fname)) {
                    if ($old && is_file($clientsDir . $old)) @unlink($clientsDir . $old);
                    $pdo->prepare("UPDATE our_clients SET logo = ? WHERE id = ?")->execute([$fname, $id]);
                }
            }
        }
        header('Location: clients.php');
        exit;
    }
}

try {
    $list = $pdo->query("SELECT * FROM our_clients ORDER BY sort_order, id")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $list = []; }

$ourTitle = getSetting('our_clients_title', 'Our clients');
$ourSub = getSetting('our_clients_subtext', '');
$pageTitle = 'Our clients';
require_once __DIR__ . '/includes/header.php';
?>
<div class="admin-page">
    <h1>Our clients <small style="font-weight:400;color:#666">(home page logo strip)</small></h1>
    <?php if (empty($list) && !isset($_GET['setup'])): ?>
    <p class="error">Table missing? Import <code>database/our_clients.sql</code> in phpMyAdmin.</p>
    <?php endif; ?>
    <?php if (isset($_GET['saved'])): ?><p class="success">Section title saved.</p><?php endif; ?>

    <h2>Section heading</h2>
    <form method="post" class="admin-form" style="max-width:520px;">
        <input type="hidden" name="save_settings" value="1">
        <label>Title</label>
        <input type="text" name="our_clients_title" value="<?php echo htmlspecialchars($ourTitle); ?>">
        <label>Subtext (optional)</label>
        <input type="text" name="our_clients_subtext" value="<?php echo htmlspecialchars($ourSub); ?>" placeholder="Trusted by brands…">
        <button type="submit" class="btn">Save</button>
    </form>

    <h2 style="margin-top:2rem;">Add client logo</h2>
    <form method="post" enctype="multipart/form-data" class="admin-form" style="max-width:520px;">
        <input type="hidden" name="add_client" value="1">
        <label>Client name *</label>
        <input type="text" name="name" required placeholder="Company name">
        <label>Logo image *</label>
        <p class="muted" style="margin:0 0 8px; font-size:0.85rem;">Recommended logo size: <strong>400×200</strong> (2:1). Prefer PNG/SVG with transparent background.</p>
        <input type="file" name="logo" accept="image/*" required>
        <label>Website URL (optional)</label>
        <input type="url" name="website_url" placeholder="https://...">
        <label>Sort order</label>
        <input type="number" name="sort_order" value="0">
        <button type="submit" class="btn">Add client</button>
    </form>

    <h2 style="margin-top:2rem;">Clients list</h2>
    <table class="admin-table">
        <thead><tr><th>Logo</th><th>Name</th><th>URL</th><th>Order</th><th>Active</th><th>Actions</th></tr></thead>
        <tbody>
            <?php foreach ($list as $c): ?>
            <tr>
                <td><?php if (is_file($clientsDir . $c['logo'])): ?><img src="<?php echo ADMIN_SITE_ROOT; ?>/uploads/clients/<?php echo htmlspecialchars($c['logo']); ?>" alt="" style="max-height:40px;"><?php else: ?>—<?php endif; ?></td>
                <td><?php echo htmlspecialchars($c['name']); ?></td>
                <td><?php echo $c['website_url'] ? htmlspecialchars(mb_substr($c['website_url'],0,40)).'…' : '—'; ?></td>
                <td><?php echo (int)$c['sort_order']; ?></td>
                <td><?php echo $c['is_active'] ? 'Yes' : 'No'; ?></td>
                <td>
                    <form method="post" style="display:inline;" onsubmit="return confirm('Delete?');">
                        <input type="hidden" name="delete_id" value="<?php echo (int)$c['id']; ?>">
                        <button type="submit" class="link-btn">Delete</button>
                    </form>
                </td>
            </tr>
            <tr><td colspan="6">
                <form method="post" enctype="multipart/form-data" style="display:flex;flex-wrap:wrap;gap:8px;align-items:flex-end;">
                    <input type="hidden" name="edit_id" value="<?php echo (int)$c['id']; ?>">
                    <input type="text" name="name" value="<?php echo htmlspecialchars($c['name']); ?>" style="width:140px;">
                    <input type="url" name="website_url" value="<?php echo htmlspecialchars($c['website_url'] ?? ''); ?>" placeholder="URL" style="width:180px;">
                    <input type="number" name="sort_order" value="<?php echo (int)$c['sort_order']; ?>" style="width:60px;">
                    <label><input type="checkbox" name="is_active" value="1" <?php echo $c['is_active'] ? 'checked' : ''; ?>> Active</label>
                    <input type="file" name="logo" accept="image/*" title="Replace logo">
                    <button type="submit" class="btn">Save</button>
                </form>
            </td></tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
