<?php
/**
 * Admin — Projects Manager
 * Path: admin/projects.php
 * Images: file upload + URL links | Videos: link only
 */
require_once 'layout-header.php';

$msg_success = '';
$msg_error   = '';
$action      = isset($_GET['action']) ? $_GET['action'] : 'list';
$edit_id     = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$conn) {
    echo "<main class='flex-1 p-6'><div class='p-4 bg-red-950/40 border border-red-800 text-red-200 text-sm rounded-xl'>ডাটাবেজ কানেক্টেড নেই!</div></main>";
    require_once 'layout-footer.php';
    exit;
}

ensure_projects_table();
$categories = get_categories(false);

if ($action === 'delete' && $edit_id > 0) {
    delete_project($edit_id) ? $msg_success = 'প্রজেক্ট মুছে ফেলা হয়েছে।' : $msg_error = 'ডিলিট ব্যর্থ।';
    $action = 'list';
}

/**
 * Upload multiple project images → relative paths like uploads/xxx.jpg
 */
function upload_project_images($field = 'image_files') {
    $saved = [];
    if (empty($_FILES[$field]) || empty($_FILES[$field]['name'])) return $saved;

    $names = $_FILES[$field]['name'];
    $tmps  = $_FILES[$field]['tmp_name'];
    $errs  = $_FILES[$field]['error'];
    if (!is_array($names)) {
        $names = [$names];
        $tmps  = [$tmps];
        $errs  = [$errs];
    }

    $dir = '../uploads/';
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    $allowed = ['jpg', 'jpeg', 'png', 'webp', 'gif'];

    foreach ($names as $i => $name) {
        if (($errs[$i] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) continue;
        if (empty($tmps[$i]) || !is_uploaded_file($tmps[$i])) continue;
        $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
        if (!in_array($ext, $allowed, true)) continue;
        $fname = time() . '_proj_' . bin2hex(random_bytes(3)) . '_' . $i . '.' . $ext;
        if (move_uploaded_file($tmps[$i], $dir . $fname)) {
            $saved[] = 'uploads/' . $fname;
        }
    }
    return $saved;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['form_action'])) {
    $project_id = intval($_POST['project_id'] ?? 0);

    // Existing URLs from textarea + newly uploaded files
    $url_images = project_decode_urls(trim($_POST['image_urls'] ?? ''));
    $uploaded   = upload_project_images('image_files');
    $all_images = array_values(array_unique(array_merge($url_images, $uploaded)));

    $data = [
        'company_name' => trim($_POST['company_name'] ?? ''),
        'category_id'  => intval($_POST['category_id'] ?? 0),
        'description'  => trim($_POST['description'] ?? ''),
        'image_urls'   => $all_images,
        'video_urls'   => trim($_POST['video_urls'] ?? ''),
        'is_active'    => isset($_POST['is_active']) ? 1 : 0,
    ];

    if ($data['company_name'] === '') {
        $msg_error = 'কোম্পানির নাম বাধ্যতামূলক।';
        $action = $project_id > 0 ? 'edit' : 'add';
        $edit_id = $project_id;
    } else {
        $ok = save_project($data, $project_id > 0 ? $project_id : 0);
        if ($ok) {
            $extra = count($uploaded) ? ' (' . count($uploaded) . 'টি ছবি আপলোড হয়েছে)' : '';
            $msg_success = 'প্রজেক্ট সেভ হয়েছে!' . $extra;
        } else {
            $msg_error = 'সেভ ব্যর্থ।';
        }
        $action = 'list';
    }
}
?>

<main class="flex-1 p-6 md:p-8 space-y-6">

    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 border-b border-slate-800/80 pb-5">
        <div>
            <h1 class="text-2xl font-black text-white uppercase tracking-wider">Projects</h1>
            <p class="text-xs text-slate-400 mt-1">ছবি: আপলোড বা লিংক · ভিডিও: শুধু লিংক</p>
        </div>
        <?php if ($action === 'list'): ?>
        <a href="?action=add" class="bg-sky-500 hover:bg-sky-600 text-slate-950 font-black px-5 py-2.5 rounded-xl text-xs uppercase flex items-center">
            <i class="fa-solid fa-plus-circle mr-2"></i> Add Project
        </a>
        <?php else: ?>
        <a href="projects.php" class="bg-slate-800 text-slate-300 px-5 py-2.5 rounded-xl text-xs uppercase flex items-center">
            <i class="fa-solid fa-arrow-left mr-2"></i> Back
        </a>
        <?php endif; ?>
    </div>

    <?php if ($msg_success): ?>
    <div class="p-4 bg-emerald-950/40 border border-emerald-800 text-emerald-200 text-xs rounded-xl"><i class="fa-solid fa-circle-check mr-2"></i><?php echo $msg_success; ?></div>
    <?php endif; ?>
    <?php if ($msg_error): ?>
    <div class="p-4 bg-red-950/40 border border-red-800 text-red-200 text-xs rounded-xl"><i class="fa-solid fa-triangle-exclamation mr-2"></i><?php echo $msg_error; ?></div>
    <?php endif; ?>

    <?php if ($action === 'add' || $action === 'edit'):
        $val = [
            'company_name' => '',
            'category_id'  => 0,
            'description'  => '',
            'image_urls'   => '',
            'video_urls'   => '',
            'is_active'    => 1,
            'images'       => [],
        ];
        if ($action === 'edit' && $edit_id > 0) {
            $row = get_project_by_id($edit_id);
            if ($row) {
                $val = [
                    'company_name' => $row['company_name'],
                    'category_id'  => intval($row['category_id'] ?? 0),
                    'description'  => $row['description'] ?? '',
                    'image_urls'   => implode("\n", $row['images'] ?? []),
                    'video_urls'   => implode("\n", $row['videos'] ?? []),
                    'is_active'    => intval($row['is_active'] ?? 1),
                    'images'       => $row['images'] ?? [],
                ];
            }
        }
    ?>
    <form method="post" action="" enctype="multipart/form-data" class="bg-slate-900 border border-slate-800/80 rounded-2xl p-6 space-y-5 max-w-3xl">
        <input type="hidden" name="form_action" value="save">
        <?php if ($action === 'edit'): ?><input type="hidden" name="project_id" value="<?php echo $edit_id; ?>"><?php endif; ?>

        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Company Name *</label>
            <input type="text" name="company_name" required value="<?php echo htmlspecialchars($val['company_name']); ?>"
                class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100" placeholder="e.g. ABC Properties Ltd">
        </div>

        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Service (Category)</label>
            <select name="category_id" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
                <option value="0">— Select category —</option>
                <?php foreach ($categories as $cat): ?>
                <option value="<?php echo $cat['id']; ?>" <?php echo intval($val['category_id']) === intval($cat['id']) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($cat['name']); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>

        <!-- Images: upload + URL -->
        <div class="space-y-3 border border-slate-800 rounded-2xl p-4">
            <p class="text-xs font-bold uppercase text-slate-300">Images <span class="text-slate-500 normal-case font-normal">(upload এবং/অথবা link — দুটোই চলবে)</span></p>

            <?php if (!empty($val['images'])): ?>
            <div class="flex flex-wrap gap-2 mb-2">
                <?php foreach ($val['images'] as $img):
                    $src = (strpos($img, 'http') === 0 || strpos($img, '//') === 0) ? $img : '../' . ltrim($img, '/');
                ?>
                <img src="<?php echo htmlspecialchars($src); ?>" alt="" class="w-16 h-16 object-cover rounded-lg border border-slate-700">
                <?php endforeach; ?>
            </div>
            <p class="text-[10px] text-slate-500 mb-2">নিচের লিস্ট এডিট/মুছে নতুন সেভ করলে আপডেট হবে। নতুন আপলোড আগের সাথে যোগ হবে।</p>
            <?php endif; ?>

            <div>
                <label class="block text-[10px] font-bold uppercase text-slate-500 mb-1.5">Select files (multiple)</label>
                <input type="file" name="image_files[]" accept="image/*" multiple
                    class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2.5 text-xs text-slate-400 file:mr-3 file:py-1 file:px-3 file:rounded-lg file:border-0 file:bg-sky-500 file:text-slate-950 file:text-xs file:font-bold">
            </div>

            <div>
                <label class="block text-[10px] font-bold uppercase text-slate-500 mb-1.5">Image URLs <span class="normal-case">(one per line)</span></label>
                <textarea name="image_urls" rows="4" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100 font-mono"
                    placeholder="https://example.com/photo1.jpg&#10;uploads/old-image.jpg"><?php echo htmlspecialchars($val['image_urls']); ?></textarea>
            </div>
        </div>

        <!-- Video: link only -->
        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Video Links <span class="normal-case text-slate-500">(শুধু লিংক — YouTube ইত্যাদি, one per line)</span></label>
            <textarea name="video_urls" rows="3" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100 font-mono"
                placeholder="https://youtu.be/xxxxx"><?php echo htmlspecialchars($val['video_urls']); ?></textarea>
        </div>

        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Details</label>
            <textarea name="description" rows="6" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100"
                placeholder="Project details..."><?php echo htmlspecialchars($val['description']); ?></textarea>
        </div>

        <label class="flex items-center gap-2 text-sm text-slate-300 cursor-pointer">
            <input type="checkbox" name="is_active" value="1" <?php echo !empty($val['is_active']) ? 'checked' : ''; ?> class="rounded border-slate-600">
            Active (show on website)
        </label>

        <button type="submit" class="bg-sky-500 hover:bg-sky-600 text-slate-950 font-black px-6 py-3 rounded-xl text-xs uppercase">
            <i class="fa-solid fa-floppy-disk mr-2"></i> Save Project
        </button>
    </form>

    <?php else:
        $projects = get_projects(0, false);
    ?>
    <div class="bg-slate-900 border border-slate-800/80 rounded-2xl overflow-hidden">
        <?php if (empty($projects)): ?>
        <div class="p-12 text-center text-slate-500 text-sm">
            <i class="fa-solid fa-briefcase text-3xl mb-3 block opacity-30"></i>
            কোনো প্রজেক্ট নেই। Add Project দিয়ে শুরু করুন।
        </div>
        <?php else: ?>
        <div class="overflow-x-auto">
            <table class="w-full text-sm text-left">
                <thead class="bg-slate-950 text-slate-400 text-xs uppercase">
                    <tr>
                        <th class="px-4 py-3">Company</th>
                        <th class="px-4 py-3">Service</th>
                        <th class="px-4 py-3">Media</th>
                        <th class="px-4 py-3">Status</th>
                        <th class="px-4 py-3 text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-800">
                    <?php foreach ($projects as $p): ?>
                    <tr class="hover:bg-slate-800/40">
                        <td class="px-4 py-3 text-slate-100 font-semibold"><?php echo htmlspecialchars($p['company_name']); ?></td>
                        <td class="px-4 py-3 text-slate-400"><?php echo htmlspecialchars($p['category_name'] ?? '—'); ?></td>
                        <td class="px-4 py-3 text-slate-400 text-xs">
                            <?php echo count($p['images']); ?> img · <?php echo count($p['videos']); ?> video
                        </td>
                        <td class="px-4 py-3">
                            <?php if (!empty($p['is_active'])): ?>
                            <span class="text-emerald-400 text-xs font-bold">Active</span>
                            <?php else: ?>
                            <span class="text-slate-500 text-xs">Hidden</span>
                            <?php endif; ?>
                        </td>
                        <td class="px-4 py-3 text-right space-x-2 whitespace-nowrap">
                            <a href="?action=edit&id=<?php echo $p['id']; ?>" class="text-sky-400 hover:underline text-xs">Edit</a>
                            <a href="?action=delete&id=<?php echo $p['id']; ?>" onclick="return confirm('Delete this project?')" class="text-red-400 hover:underline text-xs">Delete</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

</main>

<?php require_once 'layout-footer.php'; ?>
