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

$taglineOptions = [
    'Innovative Packaging Solutions for Every Business',
    'Premium Printing & Packaging Solutions Since 2015',
    'Reliable Mono Carton & Corrugated Packaging Manufacturer',
    'Smart Packaging That Protects Your Product & Brand',
    'Delivering Quality Packaging with Precision',
];

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') {

    // Company intro
    if (!empty($_POST['save_company'])) {
        try {
            $id = (int)($_POST['company_id'] ?? 0);
            $name = trim($_POST['company_name'] ?? '');
            $details = trim($_POST['company_details'] ?? '');
            $position = ($_POST['image_position'] ?? 'right') === 'left' ? 'left' : 'right';
            $tagline = trim($_POST['tagline_custom'] ?? '') ?: trim($_POST['tagline'] ?? '');
            $newImage = handleUpload('company_image', $aboutDir, 'company');
            if ($id) {
                $row = $pdo->prepare("SELECT image FROM about_company WHERE id = ?");
                $row->execute([$id]);
                $old = $row->fetch(PDO::FETCH_ASSOC);
                $image = $newImage ?: ($old['image'] ?? null);
                if ($newImage && !empty($old['image']) && is_file($aboutDir . $old['image'])) @unlink($aboutDir . $old['image']);
                $pdo->prepare("UPDATE about_company SET company_name=?, company_details=?, image=?, image_position=?, tagline=? WHERE id=?")->execute([$name, $details, $image, $position, $tagline, $id]);
            } else {
                $image = $newImage;
                $pdo->prepare("INSERT INTO about_company (row_key, company_name, company_details, image, image_position, tagline) VALUES ('main',?,?,?,?,?)")->execute([$name, $details, $image, $position, $tagline]);
            }
        } catch (Exception $e) { /* table missing */ }
        header('Location: about-edit.php?saved=1#company');
        exit;
    }

    // Growth main
    if (!empty($_POST['save_growth_main'])) {
        try {
            $id = (int)$_POST['growth_main_id'];
            $heading = trim($_POST['growth_main_heading'] ?? '');
            $desc = trim($_POST['growth_main_description'] ?? '');
            $newImage = handleUpload('growth_main_image', $aboutDir, 'growth_main');
            $stmt = $pdo->prepare("SELECT image FROM about_growth WHERE id = ?");
            $stmt->execute([$id]);
            $old = $stmt->fetch(PDO::FETCH_ASSOC);
            $image = $newImage ?: ($old['image'] ?? null);
            if ($newImage && $old && !empty($old['image']) && is_file($aboutDir . $old['image'])) @unlink($aboutDir . $old['image']);
            $pdo->prepare("UPDATE about_growth SET heading=?, description=?, image=? WHERE id=?")->execute([$heading, $desc, $image, $id]);
        } catch (Exception $e) { /* */ }
        header('Location: about-edit.php?saved=1#growth');
        exit;
    }

    // Growth future goal
    if (!empty($_POST['save_growth_future'])) {
        try {
            $id = (int)$_POST['growth_future_id'];
            $heading = trim($_POST['growth_future_heading'] ?? '');
            $desc = trim($_POST['growth_future_description'] ?? '');
            $newImage = handleUpload('growth_future_image', $aboutDir, 'future');
            $stmt = $pdo->prepare("SELECT image FROM about_growth WHERE id = ?");
            $stmt->execute([$id]);
            $old = $stmt->fetch(PDO::FETCH_ASSOC);
            $image = $newImage ?: ($old['image'] ?? null);
            if ($newImage && $old && !empty($old['image']) && is_file($aboutDir . $old['image'])) @unlink($aboutDir . $old['image']);
            $pdo->prepare("UPDATE about_growth SET heading=?, description=?, image=? WHERE id=?")->execute([$heading, $desc, $image, $id]);
        } catch (Exception $e) { /* */ }
        header('Location: about-edit.php?saved=1#growth');
        exit;
    }

    // Growth current
    if (!empty($_POST['save_growth_current'])) {
        try {
            $id = (int)$_POST['growth_current_id'];
            $heading = trim($_POST['growth_current_heading'] ?? '');
            $desc = trim($_POST['growth_current_description'] ?? '');
            $newImage = handleUpload('growth_current_image', $aboutDir, 'current');
            $stmt = $pdo->prepare("SELECT image FROM about_growth WHERE id = ?");
            $stmt->execute([$id]);
            $old = $stmt->fetch(PDO::FETCH_ASSOC);
            $image = $newImage ?: ($old['image'] ?? null);
            if ($newImage && $old && !empty($old['image']) && is_file($aboutDir . $old['image'])) @unlink($aboutDir . $old['image']);
            $pdo->prepare("UPDATE about_growth SET heading=?, description=?, image=? WHERE id=?")->execute([$heading, $desc, $image, $id]);
        } catch (Exception $e) { /* */ }
        header('Location: about-edit.php?saved=1#growth');
        exit;
    }

    // Owner
    if (!empty($_POST['save_owner'])) {
        try {
            $id = (int)($_POST['owner_id'] ?? 0);
            $name = trim($_POST['owner_name'] ?? '');
            $designation = trim($_POST['owner_designation'] ?? '');
            $desc = trim($_POST['owner_description'] ?? '');
            $newImage = handleUpload('owner_image', $aboutDir, 'owner');
            if ($id) {
                $stmt = $pdo->prepare("SELECT image FROM about_owner WHERE id = ?");
                $stmt->execute([$id]);
                $old = $stmt->fetch(PDO::FETCH_ASSOC);
                $image = $newImage ?: ($old['image'] ?? null);
                if ($newImage && $old && !empty($old['image']) && is_file($aboutDir . $old['image'])) @unlink($aboutDir . $old['image']);
                $pdo->prepare("UPDATE about_owner SET name=?, designation=?, description=?, image=? WHERE id=?")->execute([$name, $designation, $desc, $image, $id]);
            } else {
                $image = $newImage;
                $pdo->prepare("INSERT INTO about_owner (row_key, name, designation, description, image) VALUES ('main',?,?,?,?)")->execute([$name, $designation, $desc, $image]);
            }
        } catch (Exception $e) { /* */ }
        header('Location: about-edit.php?saved=1#owner');
        exit;
    }

    // Team section heading
    if (!empty($_POST['save_team_settings'])) {
        $pdo->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES ('about_team_heading', ?) ON DUPLICATE KEY UPDATE setting_value = ?")->execute([trim($_POST['about_team_heading'] ?? ''), trim($_POST['about_team_heading'] ?? '')]);
        $pdo->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES ('about_team_subtext', ?) ON DUPLICATE KEY UPDATE setting_value = ?")->execute([trim($_POST['about_team_subtext'] ?? ''), trim($_POST['about_team_subtext'] ?? '')]);
        header('Location: about-edit.php?saved=1#team');
        exit;
    }

    // Add team member
    if (!empty($_POST['add_team_member'])) {
        try {
            $name = trim($_POST['team_name'] ?? '');
            $designation = trim($_POST['team_designation'] ?? '');
            $sort = (int)($_POST['team_sort_order'] ?? 0);
            $newImage = handleUpload('team_image', $aboutDir, 'team');
            if ($name && $designation) {
                $pdo->prepare("INSERT INTO about_team (name, designation, image, sort_order) VALUES (?,?,?,?)")->execute([$name, $designation, $newImage, $sort]);
            }
        } catch (Exception $e) { /* */ }
        header('Location: about-edit.php?saved=1#team');
        exit;
    }

    // Edit team member
    if (!empty($_POST['edit_team_id'])) {
        try {
            $id = (int)$_POST['edit_team_id'];
            $name = trim($_POST['team_name'] ?? '');
            $designation = trim($_POST['team_designation'] ?? '');
            $sort = (int)($_POST['team_sort_order'] ?? 0);
            $active = isset($_POST['team_is_active']) ? 1 : 0;
            $newImage = handleUpload('team_image', $aboutDir, 'team');
            $stmt = $pdo->prepare("SELECT image FROM about_team WHERE id = ?");
            $stmt->execute([$id]);
            $old = $stmt->fetch(PDO::FETCH_ASSOC);
            $image = $newImage ?: ($old['image'] ?? null);
            if ($newImage && $old && !empty($old['image']) && is_file($aboutDir . $old['image'])) @unlink($aboutDir . $old['image']);
            $pdo->prepare("UPDATE about_team SET name=?, designation=?, image=?, sort_order=?, is_active=? WHERE id=?")->execute([$name, $designation, $image, $sort, $active, $id]);
        } catch (Exception $e) { /* */ }
        header('Location: about-edit.php?saved=1#team');
        exit;
    }

    // Delete team member
    if (!empty($_POST['delete_team_id'])) {
        try {
            $id = (int)$_POST['delete_team_id'];
            $stmt = $pdo->prepare("SELECT image FROM about_team WHERE id = ?");
            $stmt->execute([$id]);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($row && !empty($row['image']) && is_file($aboutDir . $row['image'])) @unlink($aboutDir . $row['image']);
            $pdo->prepare("DELETE FROM about_team WHERE id = ?")->execute([$id]);
        } catch (Exception $e) { /* */ }
        header('Location: about-edit.php?saved=1#team');
        exit;
    }
}

// ----- Load data
$company = null;
$growthMain = $growthFuture = $growthCurrent = null;
$owner = null;
$teamList = [];
$tablesExist = true;

try {
    $row = $pdo->query("SELECT id, company_name, company_details, image, image_position, tagline FROM about_company WHERE is_active = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($row) $company = $row;
} catch (Exception $e) { $tablesExist = false; }
if (!$company) $company = ['id' => 0, 'company_name' => 'Crimson Uni Quepack Pvt. Ltd.', 'company_details' => '', 'image' => null, 'image_position' => 'right', 'tagline' => $taglineOptions[1]];

try {
    $stmt = $pdo->query("SELECT id, section_type, heading, description, image FROM about_growth WHERE is_active = 1 ORDER BY sort_order, id");
    while ($r = $stmt->fetch(PDO::FETCH_ASSOC)) {
        if ($r['section_type'] === 'main') $growthMain = $r;
        elseif ($r['section_type'] === 'future_goal') $growthFuture = $r;
        elseif ($r['section_type'] === 'current_growth') $growthCurrent = $r;
    }
} catch (Exception $e) { $tablesExist = false; }
if (!$growthMain) $growthMain = ['id' => 0, 'heading' => 'Our Growth Journey', 'description' => '', 'image' => null];
if (!$growthFuture) $growthFuture = ['id' => 0, 'heading' => 'Future Goal', 'description' => '', 'image' => null];
if (!$growthCurrent) $growthCurrent = ['id' => 0, 'heading' => 'Current Growth', 'description' => '', 'image' => null];

try {
    $owner = $pdo->query("SELECT id, name, designation, description, image FROM about_owner WHERE is_active = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) { /* */ }
if (!$owner) $owner = ['id' => 0, 'name' => 'Leadership', 'designation' => 'Founder & Managing Director', 'description' => '', 'image' => null];

try {
    $teamList = $pdo->query("SELECT id, name, designation, image, sort_order, is_active FROM about_team ORDER BY sort_order, id")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { /* */ }

$teamHeading = getSetting('about_team_heading', 'Meet Our Team');
$teamSubtext = getSetting('about_team_subtext', 'The people behind our quality and your trust.');

$pageTitle = 'About page';
require_once __DIR__ . '/includes/header.php';
?>
<div class="admin-page">
    <h1>About page <small style="font-weight:400;color:#666">(company, growth, owner, team)</small></h1>
    <?php if (isset($_GET['saved'])): ?><p class="success">Saved.</p><?php endif; ?>
    <?php if (!$tablesExist): ?>
    <p class="error">About tables missing. Run <code>database/about_sections.sql</code> in phpMyAdmin (database: fizasie).</p>
    <?php endif; ?>
    <p><a href="<?php echo ADMIN_SITE_ROOT; ?>/about.php" target="_blank" class="btn btn-secondary">View About page</a></p>

    <!-- Company intro -->
    <section id="company" class="admin-about-block">
        <h2>Company intro</h2>
        <form method="post" enctype="multipart/form-data" class="admin-form">
            <input type="hidden" name="save_company" value="1">
            <input type="hidden" name="company_id" value="<?php echo (int)$company['id']; ?>">
            <label>Company name</label>
            <input type="text" name="company_name" value="<?php echo htmlspecialchars($company['company_name']); ?>" required>
            <label>Tagline</label>
            <select name="tagline">
                <?php foreach ($taglineOptions as $opt): ?>
                <option value="<?php echo htmlspecialchars($opt); ?>" <?php echo (isset($company['tagline']) && $company['tagline'] === $opt) ? 'selected' : ''; ?>><?php echo htmlspecialchars($opt); ?></option>
                <?php endforeach; ?>
            </select>
            <p class="muted">Or type a custom tagline below (overrides select when not empty).</p>
            <label>Custom tagline</label>
            <?php $taglineIsPreset = isset($company['tagline']) && in_array($company['tagline'], $taglineOptions, true); ?>
            <input type="text" name="tagline_custom" value="<?php echo $taglineIsPreset ? '' : htmlspecialchars($company['tagline'] ?? ''); ?>" placeholder="Leave empty to use option above">
            <label>Company details (paragraph)</label>
            <textarea name="company_details" rows="6"><?php echo htmlspecialchars($company['company_details'] ?? ''); ?></textarea>
            <label>Image position</label>
            <select name="image_position">
                <option value="right" <?php echo (isset($company['image_position']) && $company['image_position'] === 'right') ? 'selected' : ''; ?>>Image on right</option>
                <option value="left" <?php echo (isset($company['image_position']) && $company['image_position'] === 'left') ? 'selected' : ''; ?>>Image on left</option>
            </select>
            <label>Company image</label>
            <?php if (!empty($company['image']) && is_file($aboutDir . $company['image'])): ?>
            <p><img src="<?php echo ADMIN_SITE_ROOT; ?>/uploads/about/<?php echo htmlspecialchars($company['image']); ?>" alt="" style="max-width:200px; height:auto; border-radius:8px;"></p>
            <?php endif; ?>
            <input type="file" name="company_image" accept="image/*">
            <button type="submit" class="btn">Save company intro</button>
        </form>
    </section>

    <!-- Growth: main -->
    <section id="growth" class="admin-about-block">
        <h2>Company growth – main section</h2>
        <?php if ($growthMain['id']): ?>
        <form method="post" enctype="multipart/form-data" class="admin-form">
            <input type="hidden" name="save_growth_main" value="1">
            <input type="hidden" name="growth_main_id" value="<?php echo (int)$growthMain['id']; ?>">
            <label>Heading</label>
            <input type="text" name="growth_main_heading" value="<?php echo htmlspecialchars($growthMain['heading']); ?>">
            <label>Description</label>
            <textarea name="growth_main_description" rows="4"><?php echo htmlspecialchars($growthMain['description'] ?? ''); ?></textarea>
            <label>Image</label>
            <?php if (!empty($growthMain['image']) && is_file($aboutDir . $growthMain['image'])): ?>
            <p><img src="<?php echo ADMIN_SITE_ROOT; ?>/uploads/about/<?php echo htmlspecialchars($growthMain['image']); ?>" alt="" style="max-width:200px; height:auto; border-radius:8px;"></p>
            <?php endif; ?>
            <input type="file" name="growth_main_image" accept="image/*">
            <button type="submit" class="btn">Save</button>
        </form>
        <?php else: ?>
        <p class="muted">Run the database migration to add growth sections.</p>
        <?php endif; ?>

        <h3 style="margin-top:24px;">Future Goal</h3>
        <?php if ($growthFuture['id']): ?>
        <form method="post" enctype="multipart/form-data" class="admin-form">
            <input type="hidden" name="save_growth_future" value="1">
            <input type="hidden" name="growth_future_id" value="<?php echo (int)$growthFuture['id']; ?>">
            <label>Heading</label>
            <input type="text" name="growth_future_heading" value="<?php echo htmlspecialchars($growthFuture['heading']); ?>">
            <label>Description</label>
            <textarea name="growth_future_description" rows="3"><?php echo htmlspecialchars($growthFuture['description'] ?? ''); ?></textarea>
            <label>Image</label>
            <?php if (!empty($growthFuture['image']) && is_file($aboutDir . $growthFuture['image'])): ?>
            <p><img src="<?php echo ADMIN_SITE_ROOT; ?>/uploads/about/<?php echo htmlspecialchars($growthFuture['image']); ?>" alt="" style="max-width:160px; height:auto; border-radius:8px;"></p>
            <?php endif; ?>
            <input type="file" name="growth_future_image" accept="image/*">
            <button type="submit" class="btn">Save Future Goal</button>
        </form>
        <?php endif; ?>

        <h3 style="margin-top:24px;">Current Growth</h3>
        <?php if ($growthCurrent['id']): ?>
        <form method="post" enctype="multipart/form-data" class="admin-form">
            <input type="hidden" name="save_growth_current" value="1">
            <input type="hidden" name="growth_current_id" value="<?php echo (int)$growthCurrent['id']; ?>">
            <label>Heading</label>
            <input type="text" name="growth_current_heading" value="<?php echo htmlspecialchars($growthCurrent['heading']); ?>">
            <label>Description</label>
            <textarea name="growth_current_description" rows="3"><?php echo htmlspecialchars($growthCurrent['description'] ?? ''); ?></textarea>
            <label>Image</label>
            <?php if (!empty($growthCurrent['image']) && is_file($aboutDir . $growthCurrent['image'])): ?>
            <p><img src="<?php echo ADMIN_SITE_ROOT; ?>/uploads/about/<?php echo htmlspecialchars($growthCurrent['image']); ?>" alt="" style="max-width:160px; height:auto; border-radius:8px;"></p>
            <?php endif; ?>
            <input type="file" name="growth_current_image" accept="image/*">
            <button type="submit" class="btn">Save Current Growth</button>
        </form>
        <?php endif; ?>
    </section>

    <!-- Owner -->
    <section id="owner" class="admin-about-block">
        <h2>Owner / leadership</h2>
        <form method="post" enctype="multipart/form-data" class="admin-form">
            <input type="hidden" name="save_owner" value="1">
            <input type="hidden" name="owner_id" value="<?php echo (int)$owner['id']; ?>">
            <label>Name</label>
            <input type="text" name="owner_name" value="<?php echo htmlspecialchars($owner['name']); ?>" required>
            <label>Designation</label>
            <input type="text" name="owner_designation" value="<?php echo htmlspecialchars($owner['designation']); ?>">
            <label>Description</label>
            <textarea name="owner_description" rows="4"><?php echo htmlspecialchars($owner['description'] ?? ''); ?></textarea>
            <label>Photo</label>
            <?php if (!empty($owner['image']) && is_file($aboutDir . $owner['image'])): ?>
            <p><img src="<?php echo ADMIN_SITE_ROOT; ?>/uploads/about/<?php echo htmlspecialchars($owner['image']); ?>" alt="" style="max-width:120px; height:auto; border-radius:8px;"></p>
            <?php endif; ?>
            <input type="file" name="owner_image" accept="image/*">
            <button type="submit" class="btn">Save owner</button>
        </form>
    </section>

    <!-- Team section heading + members -->
    <section id="team" class="admin-about-block">
        <h2>Meet our team</h2>
        <form method="post" class="admin-form">
            <input type="hidden" name="save_team_settings" value="1">
            <label>Section heading</label>
            <input type="text" name="about_team_heading" value="<?php echo htmlspecialchars($teamHeading); ?>">
            <label>Short description</label>
            <input type="text" name="about_team_subtext" value="<?php echo htmlspecialchars($teamSubtext); ?>" placeholder="The people behind...">
            <button type="submit" class="btn">Save heading</button>
        </form>

        <h3 style="margin-top:24px;">Add team member</h3>
        <form method="post" enctype="multipart/form-data" class="admin-form inline-form">
            <input type="hidden" name="add_team_member" value="1">
            <input type="text" name="team_name" placeholder="Name" required style="width:140px;">
            <input type="text" name="team_designation" placeholder="Designation" required style="width:160px;">
            <input type="number" name="team_sort_order" value="0" style="width:70px;" placeholder="Order">
            <input type="file" name="team_image" accept="image/*" title="Photo">
            <button type="submit" class="btn">Add</button>
        </form>

        <h3 style="margin-top:24px;">Team list (first 4 show on About page)</h3>
        <table class="admin-table">
            <thead><tr><th>Photo</th><th>Name</th><th>Designation</th><th>Order</th><th>Active</th><th>Actions</th></tr></thead>
            <tbody>
                <?php foreach ($teamList as $t): ?>
                <tr>
                    <td>
                        <?php if (!empty($t['image']) && is_file($aboutDir . $t['image'])): ?>
                        <img src="<?php echo ADMIN_SITE_ROOT; ?>/uploads/about/<?php echo htmlspecialchars($t['image']); ?>" alt="" style="max-height:40px; border-radius:50%;">
                        <?php else: ?>—<?php endif; ?>
                    </td>
                    <td><?php echo htmlspecialchars($t['name']); ?></td>
                    <td><?php echo htmlspecialchars($t['designation']); ?></td>
                    <td><?php echo (int)$t['sort_order']; ?></td>
                    <td><?php echo $t['is_active'] ? 'Yes' : 'No'; ?></td>
                    <td>
                        <form method="post" style="display:inline;" onsubmit="return confirm('Delete this member?');">
                            <input type="hidden" name="delete_team_id" value="<?php echo (int)$t['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_team_id" value="<?php echo (int)$t['id']; ?>">
                            <input type="text" name="team_name" value="<?php echo htmlspecialchars($t['name']); ?>" placeholder="Name" style="width:130px;">
                            <input type="text" name="team_designation" value="<?php echo htmlspecialchars($t['designation']); ?>" placeholder="Designation" style="width:150px;">
                            <input type="number" name="team_sort_order" value="<?php echo (int)$t['sort_order']; ?>" style="width:60px;">
                            <label><input type="checkbox" name="team_is_active" value="1" <?php echo $t['is_active'] ? 'checked' : ''; ?>> Active</label>
                            <input type="file" name="team_image" accept="image/*" title="Replace photo">
                            <button type="submit" class="btn">Save</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php if (empty($teamList)): ?>
        <p class="muted">No team members yet. Add above or run <code>database/about_sections.sql</code> to seed 4 members.</p>
        <?php endif; ?>
    </section>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
