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

function handleUpload($fileKey, $dir, $prefix = 'img') {
    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;
}

// ----- POST handlers
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!empty($_POST['save_quality_main'])) {
        try {
            $heading = trim($_POST['quality_heading'] ?? '');
            $short = trim($_POST['quality_short_description'] ?? '');
            $pdo->prepare("INSERT INTO quality_policy_main (row_key, heading, short_description) VALUES ('main',?,?) ON DUPLICATE KEY UPDATE heading=VALUES(heading), short_description=VALUES(short_description)")->execute([$heading, $short]);
        } catch (Exception $e) { /* */ }
        header('Location: tech-quality-edit.php?saved=1#quality');
        exit;
    }

    if (!empty($_POST['save_quality_item'])) {
        try {
            $id = (int)$_POST['quality_item_id'];
            $name = trim($_POST['quality_item_name'] ?? '');
            $shortDesc = trim($_POST['quality_item_short'] ?? '');
            $slug = trim($_POST['quality_item_slug'] ?? '');
            $detailHeading = trim($_POST['quality_item_detail_heading'] ?? '');
            $detailDesc = trim($_POST['quality_item_detail_desc'] ?? '');
            $detailContent = trim($_POST['quality_item_detail_content'] ?? '');
            $newImage = handleUpload('quality_item_image', $techDir, 'quality');
            $stmt = $pdo->prepare("SELECT image FROM quality_policy_items WHERE id = ?");
            $stmt->execute([$id]);
            $old = $stmt->fetch(PDO::FETCH_ASSOC);
            $image = $newImage ?: ($old['image'] ?? null);
            if ($newImage && $old && !empty($old['image']) && is_file($techDir . $old['image'])) @unlink($techDir . $old['image']);
            $pdo->prepare("UPDATE quality_policy_items SET name=?, short_description=?, slug=?, detail_heading=?, detail_description=?, detail_content=?, image=? WHERE id=?")->execute([$name, $shortDesc, $slug, $detailHeading, $detailDesc, $detailContent, $image, $id]);
        } catch (Exception $e) { /* */ }
        header('Location: tech-quality-edit.php?saved=1#quality');
        exit;
    }

    if (!empty($_POST['save_plant_main'])) {
        try {
            $heading = trim($_POST['plant_heading'] ?? '');
            $longDesc = trim($_POST['plant_long_description'] ?? '');
            $newImage = handleUpload('plant_image', $techDir, 'plant');
            $stmt = $pdo->prepare("SELECT image FROM plant_machinery_main WHERE row_key = 'main'");
            $stmt->execute();
            $old = $stmt->fetch(PDO::FETCH_ASSOC);
            $image = $newImage ?: ($old['image'] ?? null);
            if ($newImage && $old && !empty($old['image']) && is_file($techDir . $old['image'])) @unlink($techDir . $old['image']);
            $pdo->prepare("INSERT INTO plant_machinery_main (row_key, heading, long_description, image) VALUES ('main',?,?,?) ON DUPLICATE KEY UPDATE heading=VALUES(heading), long_description=VALUES(long_description), image=COALESCE(VALUES(image), image)")->execute([$heading, $longDesc, $image]);
        } catch (Exception $e) { /* */ }
        header('Location: tech-quality-edit.php?saved=1#plant');
        exit;
    }

    if (!empty($_POST['save_plant_card'])) {
        try {
            $id = (int)$_POST['plant_card_id'];
            $name = trim($_POST['plant_card_name'] ?? '');
            $shortDesc = trim($_POST['plant_card_short'] ?? '');
            $sort = (int)($_POST['plant_card_sort'] ?? 0);
            $active = isset($_POST['plant_card_active']) ? 1 : 0;
            $pdo->prepare("UPDATE plant_machinery_cards SET name=?, short_description=?, sort_order=?, is_active=? WHERE id=?")->execute([$name, $shortDesc, $sort, $active, $id]);
        } catch (Exception $e) { /* */ }
        header('Location: tech-quality-edit.php?saved=1#plant');
        exit;
    }
}

// Load data
$qualityMain = ['heading' => 'Quality Policy', 'short_description' => ''];
$qualityItems = [];
$plantMain = ['heading' => 'Plant & Machinery', 'long_description' => '', 'image' => null];
$plantCards = [];
$tablesExist = true;

try {
    $row = $pdo->query("SELECT heading, short_description FROM quality_policy_main LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($row) $qualityMain = $row;
    $qualityItems = $pdo->query("SELECT * FROM quality_policy_items ORDER BY sort_order, id")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $tablesExist = false; }

try {
    $row = $pdo->query("SELECT heading, long_description, image FROM plant_machinery_main LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($row) $plantMain = $row;
    $plantCards = $pdo->query("SELECT * FROM plant_machinery_cards ORDER BY sort_order, id")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { /* */ }

$pageTitle = 'Technology & Quality';
require_once __DIR__ . '/includes/header.php';
?>
<div class="admin-page">
    <h1>Technology &amp; Quality <small style="font-weight:400;color:#666">(Quality policy + Plant &amp; Machinery)</small></h1>
    <?php if (isset($_GET['saved'])): ?><p class="success">Saved.</p><?php endif; ?>
    <?php if (!$tablesExist): ?>
    <p class="error">Tables missing. Run <code>database/tech_quality_tables.sql</code> in phpMyAdmin (database: fizasie).</p>
    <?php endif; ?>
    <p>
        <a href="<?php echo ADMIN_SITE_ROOT; ?>/quality-policy.php" target="_blank" class="btn btn-secondary">View Quality policy</a>
        <a href="<?php echo ADMIN_SITE_ROOT; ?>/plant-machinery.php" target="_blank" class="btn btn-secondary">View Plant &amp; Machinery</a>
    </p>

    <!-- Quality policy main -->
    <section id="quality" class="admin-about-block">
        <h2>1. Quality policy page – main</h2>
        <form method="post" class="admin-form">
            <input type="hidden" name="save_quality_main" value="1">
            <label>Heading</label>
            <input type="text" name="quality_heading" value="<?php echo htmlspecialchars($qualityMain['heading']); ?>">
            <label>Short description</label>
            <textarea name="quality_short_description" rows="3"><?php echo htmlspecialchars($qualityMain['short_description'] ?? ''); ?></textarea>
            <button type="submit" class="btn">Save</button>
        </form>

        <h3 style="margin-top:28px;">Quality policy cards (4) – name, short description, More details page</h3>
        <?php foreach ($qualityItems as $q): ?>
        <div class="admin-form-block" style="margin-bottom:24px; padding:20px; border:1px solid #e2e8f0; border-radius:12px;">
            <form method="post" enctype="multipart/form-data" class="admin-form">
                <input type="hidden" name="save_quality_item" value="1">
                <input type="hidden" name="quality_item_id" value="<?php echo (int)$q['id']; ?>">
                <label>Card name</label>
                <input type="text" name="quality_item_name" value="<?php echo htmlspecialchars($q['name']); ?>" required>
                <label>Card short description</label>
                <textarea name="quality_item_short" rows="2"><?php echo htmlspecialchars($q['short_description'] ?? ''); ?></textarea>
                <label>Slug (URL, e.g. quality-commitment)</label>
                <input type="text" name="quality_item_slug" value="<?php echo htmlspecialchars($q['slug'] ?? ''); ?>">
                <label>Detail page – heading</label>
                <input type="text" name="quality_item_detail_heading" value="<?php echo htmlspecialchars($q['detail_heading'] ?? ''); ?>">
                <label>Detail page – short description</label>
                <textarea name="quality_item_detail_desc" rows="2"><?php echo htmlspecialchars($q['detail_description'] ?? ''); ?></textarea>
                <label>Detail page – full content (use • for bullets, new lines for paragraphs)</label>
                <textarea name="quality_item_detail_content" rows="8"><?php echo htmlspecialchars($q['detail_content'] ?? ''); ?></textarea>
                <label>Detail page image</label>
                <?php if (!empty($q['image']) && is_file($techDir . $q['image'])): ?>
                <p><img src="<?php echo ADMIN_SITE_ROOT; ?>/uploads/tech_quality/<?php echo htmlspecialchars($q['image']); ?>" alt="" style="max-width:180px; height:auto; border-radius:8px;"></p>
                <?php endif; ?>
                <input type="file" name="quality_item_image" accept="image/*">
                <button type="submit" class="btn">Save this card</button>
            </form>
        </div>
        <?php endforeach; ?>
    </section>

    <!-- Plant & Machinery -->
    <section id="plant" class="admin-about-block">
        <h2>2. Plant &amp; Machinery – single page</h2>
        <form method="post" enctype="multipart/form-data" class="admin-form">
            <input type="hidden" name="save_plant_main" value="1">
            <label>Heading</label>
            <input type="text" name="plant_heading" value="<?php echo htmlspecialchars($plantMain['heading']); ?>">
            <label>Long description</label>
            <textarea name="plant_long_description" rows="8"><?php echo htmlspecialchars($plantMain['long_description'] ?? ''); ?></textarea>
            <label>Page image</label>
            <?php if (!empty($plantMain['image']) && is_file($techDir . $plantMain['image'])): ?>
            <p><img src="<?php echo ADMIN_SITE_ROOT; ?>/uploads/tech_quality/<?php echo htmlspecialchars($plantMain['image']); ?>" alt="" style="max-width:220px; height:auto; border-radius:8px;"></p>
            <?php endif; ?>
            <input type="file" name="plant_image" accept="image/*">
            <button type="submit" class="btn">Save Plant &amp; Machinery main</button>
        </form>

        <h3 style="margin-top:28px;">Our Key Machinery – 5 cards (name, short description)</h3>
        <table class="admin-table">
            <thead><tr><th>Name</th><th>Short description</th><th>Order</th><th>Active</th><th>Actions</th></tr></thead>
            <tbody>
                <?php foreach ($plantCards as $c): ?>
                <tr>
                    <td><?php echo htmlspecialchars($c['name']); ?></td>
                    <td><?php echo htmlspecialchars(mb_substr($c['short_description'] ?? '', 0, 60)); ?>…</td>
                    <td><?php echo (int)$c['sort_order']; ?></td>
                    <td><?php echo $c['is_active'] ? 'Yes' : 'No'; ?></td>
                    <td>—</td>
                </tr>
                <tr>
                    <td colspan="5">
                        <form method="post" class="admin-form" style="max-width:100%;">
                            <input type="hidden" name="save_plant_card" value="1">
                            <input type="hidden" name="plant_card_id" value="<?php echo (int)$c['id']; ?>">
                            <input type="text" name="plant_card_name" value="<?php echo htmlspecialchars($c['name']); ?>" placeholder="Name" style="width:220px;">
                            <textarea name="plant_card_short" rows="2" placeholder="Short description" style="width:100%; max-width:480px;"><?php echo htmlspecialchars($c['short_description'] ?? ''); ?></textarea>
                            <input type="number" name="plant_card_sort" value="<?php echo (int)$c['sort_order']; ?>" style="width:70px;">
                            <label><input type="checkbox" name="plant_card_active" value="1" <?php echo $c['is_active'] ? 'checked' : ''; ?>> Active</label>
                            <button type="submit" class="btn">Save</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php if (empty($plantCards)): ?>
        <p class="muted">Run <code>database/tech_quality_tables.sql</code> to seed the 5 cards.</p>
        <?php endif; ?>
    </section>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
