����JFIF��`�`�����Viewing File: /home/u820193700/domains/spiti2026im.in/public_html/api/admin_actions.php
<?php
require_once 'db_connect.php';
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit; }

session_start();

$action = $_GET['action'] ?? '';

// --- CSV Export (requires admin session) ---
if ($action === 'export_csv') {
    if (!isset($_SESSION['admin_id'])) { http_response_code(403); exit; }
    $type = $_GET['type'] ?? 'registrations';

    if ($type === 'registrations') {
        $rows = $pdo->query("SELECT name, phone, email, city, bike, blood_group, tshirt_size, status, payment_status, notes, created_at FROM registrations ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
        $filename = 'spiti2026_registrations_' . date('Ymd') . '.csv';
    } else {
        $rows = $pdo->query("SELECT name, phone, email, city, status, created_at FROM interests ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
        $filename = 'spiti2026_interests_' . date('Ymd') . '.csv';
    }

    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Cache-Control: no-cache, no-store, must-revalidate');
    $out = fopen('php://output', 'w');
    fprintf($out, chr(0xEF) . chr(0xBB) . chr(0xBF)); // UTF-8 BOM for Excel
    if (!empty($rows)) {
        fputcsv($out, array_keys($rows[0]));
        foreach ($rows as $row) fputcsv($out, $row);
    }
    fclose($out);
    exit;
}

// --- All other actions require admin session ---
if (!isset($_SESSION['admin_id'])) {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if ($action === 'get_data') {
        $regs     = $pdo->query("SELECT * FROM registrations ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
        $interests= $pdo->query("SELECT * FROM interests ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
        $qa       = $pdo->query("SELECT * FROM qa ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
        $contacts = $pdo->query("SELECT * FROM contacts ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
        $hotels   = $pdo->query("SELECT * FROM hotels ORDER BY display_order ASC")->fetchAll(PDO::FETCH_ASSOC);
        $gallery  = $pdo->query("SELECT * FROM gallery ORDER BY sort_order ASC, created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['regs' => $regs, 'interests' => $interests, 'qa' => $qa, 'contacts' => $contacts, 'hotels' => $hotels, 'gallery' => $gallery]);
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'update_reg') {
        $stmt = $pdo->prepare("UPDATE registrations SET status = ?, payment_status = ?, notes = ? WHERE uid = ?");
        $stmt->execute([$input['status'], $input['payment_status'], $input['notes'] ?? '', $input['uid']]);
        echo json_encode(['success' => true]);
    } elseif ($action === 'delete_reg') {
        $stmt = $pdo->prepare("DELETE FROM registrations WHERE uid = ?");
        $stmt->execute([$input['uid']]);
        echo json_encode(['success' => true]);
    } elseif ($action === 'delete_interest') {
        $stmt = $pdo->prepare("DELETE FROM interests WHERE uid = ?");
        $stmt->execute([$input['uid']]);
        echo json_encode(['success' => true]);
    } elseif ($action === 'answer_qa') {
        $stmt = $pdo->prepare("UPDATE qa SET answer = ?, published = ? WHERE uid = ?");
        $stmt->execute([$input['answer'], $input['published'] ? 1 : 0, $input['uid']]);
        echo json_encode(['success' => true]);
    } elseif ($action === 'delete_qa') {
        $stmt = $pdo->prepare("DELETE FROM qa WHERE uid = ?");
        $stmt->execute([$input['uid']]);
        echo json_encode(['success' => true]);
    } elseif ($action === 'add_contact') {
        $stmt = $pdo->prepare("INSERT INTO contacts (name, phone, email, city, source) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([
            $input['name'] ?? '',
            $input['phone'] ?? '',
            $input['email'] ?? null,
            $input['city'] ?? null,
            $input['source'] ?? null
        ]);
        if ($stmt->rowCount() > 0) {
            $newId = $pdo->lastInsertId();
            $pdo->query("UPDATE contacts SET uid = $newId WHERE id = $newId");
        }
        echo json_encode(['success' => true]);
    } elseif ($action === 'update_hotel') {
        $stmt = $pdo->prepare("UPDATE hotels SET name = ?, day_location = ?, rooms_needed = ?, rate_estimate = ?, contact = ?, notes = ?, status = ? WHERE uid = ?");
        $stmt->execute([
            $input['name'],
            $input['day_location'],
            $input['rooms_needed'],
            $input['rate_estimate'],
            $input['contact'],
            $input['notes'],
            $input['status'],
            $input['uid']
        ]);
        echo json_encode(['success' => true]);
    } elseif ($action === 'add_gallery_item') {
        // Handle multipart form data
        $type = $_POST['type'] ?? 'image';
        $title = $_POST['title'] ?? '';
        $url = $_POST['url'] ?? '';
        $file_uid = uniqid('g', true); // For filename only
        $error = null;

        // Look in ../backend/uploads/ first (for 3-folder structure)
        // Fallback to ../uploads/ (for flat structure)
        $target_dir = __DIR__ . '/../backend/uploads/';
        if (!is_dir($target_dir)) {
            $target_dir = __DIR__ . '/../uploads/';
        }
        
        if (!is_dir($target_dir)) {
            @mkdir($target_dir, 0755, true);
        }

        if ($type === 'image' || $type === 'video') {
            if (isset($_FILES['media_file']) && $_FILES['media_file']['error'] === UPLOAD_ERR_OK) {
                $file = $_FILES['media_file'];
                $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

                // --- MIME type whitelist ---
                $allowed_image_mime = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
                $allowed_video_mime = ['video/mp4', 'video/webm', 'video/quicktime'];
                $allowed_mime = ($type === 'image') ? $allowed_image_mime : $allowed_video_mime;
                $allowed_ext  = ($type === 'image') ? ['jpg', 'jpeg', 'png', 'webp', 'gif'] : ['mp4', 'webm', 'mov'];

                // Get actual MIME from file content (not the browser-supplied type)
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $actual_mime = finfo_file($finfo, $file['tmp_name']);
                finfo_close($finfo);

                if (!in_array($actual_mime, $allowed_mime) || !in_array($ext, $allowed_ext)) {
                    $error = 'Invalid file type. Only ' . implode(', ', $allowed_ext) . ' files are allowed.';
                } elseif ($file['size'] > 50 * 1024 * 1024) { // 50MB max
                    $error = 'File too large. Maximum size is 50MB.';
                } else {
                    $newName = $file_uid . '.' . $ext;
                    $target = $target_dir . $newName;
                    if (move_uploaded_file($file['tmp_name'], $target)) {
                        $url = 'uploads/' . $newName; // Keep DB URL format consistent
                    } else {
                        $error = 'Failed to move uploaded file to ' . $target_dir . '. Check directory permissions.';
                    }
                }
            } else {
                $error = 'No file uploaded or upload error code: ' . ($_FILES['media_file']['error'] ?? 'missing');
            }
        } elseif ($type === 'youtube') {
            // Basic youtube ID extraction
            if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match)) {
                $url = 'https://www.youtube.com/embed/' . $match[1];
            }
        }

        if ($error) {
            echo json_encode(['success' => false, 'error' => $error]);
            exit;
        }

        $stmt = $pdo->prepare("INSERT INTO gallery (type, url, title) VALUES (?, ?, ?)");
        $stmt->execute([$type, $url, $title]);
        if ($stmt->rowCount() > 0) {
            $newId = $pdo->lastInsertId();
            $pdo->query("UPDATE gallery SET uid = $newId WHERE id = $newId");
        }
        echo json_encode(['success' => true]);
    } elseif ($action === 'delete_gallery_item') {
        // Delete local file if it exists
        $stmt = $pdo->prepare("SELECT url FROM gallery WHERE uid = ?");
        $stmt->execute([$input['uid']]);
        $item = $stmt->fetch();
        if ($item && strpos($item['url'], 'uploads/') === 0) {
            $filename = basename($item['url']);
            @unlink($target_dir . $filename);
        }
        $stmt = $pdo->prepare("DELETE FROM gallery WHERE uid = ?");
        $stmt->execute([$input['uid']]);
        echo json_encode(['success' => true]);
    }
}
Back to Directory �������}�!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz�������������������������������������������������������������������������������� ������w�!1AQaq"2�B���� #3R�br� $4�%�&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz������������������������������������������������������������������������ ��?��_��+��?��(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(���(�����