<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
// Single AJAX handler for all Social Media (SM) admin actions

if (session_status() === PHP_SESSION_NONE) session_start();

$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (file_exists($config_path)) {
    include($config_path);
} else {
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}

// Verify admin
$stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin || $admin['is_admin'] != 1) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized access']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
    exit();
}

$action = trim($_POST['action'] ?? '');

switch ($action) {

    // ──────────────────────────────────────────────
    // CATEGORY: ADD
    // ──────────────────────────────────────────────
    case 'add_category':
        $name  = trim($_POST['category_name']  ?? '');
        $image = trim($_POST['category_image'] ?? '');
        if (empty($name)) { echo json_encode(['status'=>'0','msg'=>'Category name is required']); exit(); }
        try {
            $stmt = $pdo->prepare("INSERT INTO sm_categories (category_name, category_image, status, created_at) VALUES (:name, :image, 1, NOW())");
            $stmt->execute(['name' => $name, 'image' => $image]);
            echo json_encode(['status'=>'1','msg'=>'Category "' . htmlspecialchars($name) . '" added successfully']);
        } catch (PDOException $e) {
            echo json_encode(['status'=>'0','msg'=>'Database error: ' . $e->getMessage()]);
        }
        break;

    // ──────────────────────────────────────────────
    // CATEGORY: EDIT
    // ──────────────────────────────────────────────
    case 'edit_category':
        $id     = filter_var($_POST['id'] ?? 0, FILTER_VALIDATE_INT);
        $name   = trim($_POST['category_name']  ?? '');
        $image  = trim($_POST['category_image'] ?? '');
        $status = in_array($_POST['status'] ?? '', ['0','1']) ? $_POST['status'] : '1';
        if (!$id)    { echo json_encode(['status'=>'0','msg'=>'Invalid category ID']); exit(); }
        if (!$name)  { echo json_encode(['status'=>'0','msg'=>'Category name is required']); exit(); }
        try {
            $stmt = $pdo->prepare("UPDATE sm_categories SET category_name=:name, category_image=:image, status=:status WHERE id=:id");
            $stmt->execute(['name'=>$name,'image'=>$image,'status'=>$status,'id'=>$id]);
            echo json_encode(['status'=>'1','msg'=>'Category updated successfully']);
        } catch (PDOException $e) {
            echo json_encode(['status'=>'0','msg'=>'Database error: ' . $e->getMessage()]);
        }
        break;

    // ──────────────────────────────────────────────
    // CATEGORY: DELETE
    // ──────────────────────────────────────────────
    case 'delete_category':
        $id = filter_var($_POST['id'] ?? 0, FILTER_VALIDATE_INT);
        if (!$id) { echo json_encode(['status'=>'0','msg'=>'Invalid category ID']); exit(); }
        try {
            // Check exists
            $chk = $pdo->prepare("SELECT category_name FROM sm_categories WHERE id=:id LIMIT 1");
            $chk->execute(['id'=>$id]);
            $cat = $chk->fetch(PDO::FETCH_ASSOC);
            if (!$cat) { echo json_encode(['status'=>'0','msg'=>'Category not found']); exit(); }
            // Delete (services cascade if FK set, otherwise delete manually)
            $pdo->prepare("DELETE FROM sm_services WHERE category_id=:id")->execute(['id'=>$id]);
            $pdo->prepare("DELETE FROM sm_categories WHERE id=:id")->execute(['id'=>$id]);
            echo json_encode(['status'=>'1','msg'=>'Category "' . htmlspecialchars($cat['category_name']) . '" and its services deleted successfully']);
        } catch (PDOException $e) {
            echo json_encode(['status'=>'0','msg'=>'Database error: ' . $e->getMessage()]);
        }
        break;

    // ──────────────────────────────────────────────
    // SERVICE: ADD
    // ──────────────────────────────────────────────
    case 'add_service':
        $cat_id  = filter_var($_POST['category_id'] ?? 0, FILTER_VALIDATE_INT);
        $name    = trim($_POST['service_name']        ?? '');
        $desc    = trim($_POST['service_description'] ?? '');
        $amount  = filter_var($_POST['amount'] ?? 0, FILTER_VALIDATE_FLOAT);
        $preview = trim($_POST['preview_link']        ?? '');
        $creds   = trim($_POST['login_credentials']   ?? '');
        if (!$cat_id || !$name || !$desc || !$amount || !$creds) {
            echo json_encode(['status'=>'0','msg'=>'Please fill in all required fields']); exit();
        }
        try {
            $stmt = $pdo->prepare("INSERT INTO sm_services (category_id, service_name, service_description, amount, preview_link, login_credentials, status, created_at)
                                   VALUES (:cat, :name, :desc, :amount, :preview, :creds, 'available', NOW())");
            $stmt->execute(['cat'=>$cat_id,'name'=>$name,'desc'=>$desc,'amount'=>$amount,'preview'=>$preview,'creds'=>$creds]);
            echo json_encode(['status'=>'1','msg'=>'Service "' . htmlspecialchars($name) . '" added successfully']);
        } catch (PDOException $e) {
            echo json_encode(['status'=>'0','msg'=>'Database error: ' . $e->getMessage()]);
        }
        break;

    // ──────────────────────────────────────────────
    // SERVICE: EDIT
    // ──────────────────────────────────────────────
    case 'edit_service':
        $id      = filter_var($_POST['id'] ?? 0, FILTER_VALIDATE_INT);
        $cat_id  = filter_var($_POST['category_id'] ?? 0, FILTER_VALIDATE_INT);
        $name    = trim($_POST['service_name']        ?? '');
        $desc    = trim($_POST['service_description'] ?? '');
        $amount  = filter_var($_POST['amount'] ?? 0, FILTER_VALIDATE_FLOAT);
        $preview = trim($_POST['preview_link']        ?? '');
        $creds   = trim($_POST['login_credentials']   ?? '');
        $status  = in_array($_POST['status'] ?? '', ['available','sold','pending']) ? $_POST['status'] : 'available';
        if (!$id || !$name || !$amount) {
            echo json_encode(['status'=>'0','msg'=>'Invalid input data']); exit();
        }
        try {
            $stmt = $pdo->prepare("UPDATE sm_services SET category_id=:cat, service_name=:name, service_description=:desc,
                                   amount=:amount, preview_link=:preview, login_credentials=:creds, status=:status
                                   WHERE id=:id");
            $stmt->execute(['cat'=>$cat_id,'name'=>$name,'desc'=>$desc,'amount'=>$amount,'preview'=>$preview,'creds'=>$creds,'status'=>$status,'id'=>$id]);
            echo json_encode(['status'=>'1','msg'=>'Service updated successfully']);
        } catch (PDOException $e) {
            echo json_encode(['status'=>'0','msg'=>'Database error: ' . $e->getMessage()]);
        }
        break;

    // ──────────────────────────────────────────────
    // SERVICE: DELETE
    // ──────────────────────────────────────────────
    case 'delete_service':
        $id = filter_var($_POST['id'] ?? 0, FILTER_VALIDATE_INT);
        if (!$id) { echo json_encode(['status'=>'0','msg'=>'Invalid service ID']); exit(); }
        try {
            $chk = $pdo->prepare("SELECT service_name FROM sm_services WHERE id=:id LIMIT 1");
            $chk->execute(['id'=>$id]);
            $svc = $chk->fetch(PDO::FETCH_ASSOC);
            if (!$svc) { echo json_encode(['status'=>'0','msg'=>'Service not found']); exit(); }
            $pdo->prepare("DELETE FROM sm_services WHERE id=:id")->execute(['id'=>$id]);
            echo json_encode(['status'=>'1','msg'=>'Service "' . htmlspecialchars($svc['service_name']) . '" deleted successfully']);
        } catch (PDOException $e) {
            echo json_encode(['status'=>'0','msg'=>'Database error: ' . $e->getMessage()]);
        }
        break;

    // ──────────────────────────────────────────────
    // SM TRANSACTION: APPROVE REFUND
    // ──────────────────────────────────────────────
    case 'approve_sm_refund':
        $id = filter_var($_POST['id'] ?? 0, FILTER_VALIDATE_INT);
        if (!$id) { echo json_encode(['status'=>'0','msg'=>'Invalid transaction ID']); exit(); }
        try {
            $stmt = $pdo->prepare("SELECT * FROM sm_purchases WHERE id=:id AND status='refund_pending' LIMIT 1");
            $stmt->execute(['id'=>$id]);
            $purchase = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$purchase) { echo json_encode(['status'=>'0','msg'=>'Transaction not found or not in refund pending status']); exit(); }

            $pdo->beginTransaction();

            // Credit user main_balance
            $pdo->prepare("UPDATE users SET main_balance = main_balance + :amount WHERE id=:user_id")
                ->execute(['amount'=>$purchase['amount'],'user_id'=>$purchase['user_id']]);

            // Mark purchase as refunded
            $pdo->prepare("UPDATE sm_purchases SET status='refunded', refund_date=NOW() WHERE id=:id")
                ->execute(['id'=>$id]);

            // Set service back to available
            $pdo->prepare("UPDATE sm_services SET status='available' WHERE id=:sid")
                ->execute(['sid'=>$purchase['service_id']]);

            // Log refund in transactions table
            $txn_ref = 'SMREF_' . strtoupper(substr(md5(uniqid()), 0, 10));
            $pdo->prepare("INSERT INTO transactions (user_id, transaction_ref, payment_gateway, transaction_type, amount, currency, status, created_at)
                            VALUES (:uid, :ref, 'manual', 'refund', :amount, 'NGN', 'successful', NOW())")
                ->execute(['uid'=>$purchase['user_id'],'ref'=>$txn_ref,'amount'=>$purchase['amount']]);

            $pdo->commit();
            echo json_encode(['status'=>'1','msg'=>'Refund approved. $' . number_format($purchase['amount'],2) . ' credited to user balance.']);
        } catch (PDOException $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            echo json_encode(['status'=>'0','msg'=>'Database error: ' . $e->getMessage()]);
        }
        break;

    // ──────────────────────────────────────────────
    // SM TRANSACTION: CHANGE STATUS
    // ──────────────────────────────────────────────
    case 'change_sm_status':
        $id         = filter_var($_POST['id'] ?? 0, FILTER_VALIDATE_INT);
        $new_status = trim($_POST['new_status'] ?? '');
        $allowed    = ['completed','cancelled','refund_pending','refunded'];
        if (!$id || !in_array($new_status, $allowed)) {
            echo json_encode(['status'=>'0','msg'=>'Invalid input']); exit();
        }
        try {
            $chk = $pdo->prepare("SELECT id FROM sm_purchases WHERE id=:id LIMIT 1");
            $chk->execute(['id'=>$id]);
            if (!$chk->fetch()) { echo json_encode(['status'=>'0','msg'=>'Transaction not found']); exit(); }
            $pdo->prepare("UPDATE sm_purchases SET status=:status WHERE id=:id")
                ->execute(['status'=>$new_status,'id'=>$id]);
            echo json_encode(['status'=>'1','msg'=>'Status updated to "' . ucwords(str_replace('_',' ',$new_status)) . '" successfully']);
        } catch (PDOException $e) {
            echo json_encode(['status'=>'0','msg'=>'Database error: ' . $e->getMessage()]);
        }
        break;

    // ──────────────────────────────────────────────
    // DELETE ALL SMM SERVICES
    // ──────────────────────────────────────────────
    case 'delete_all_services':
        try {
            $count = (int)$pdo->query("SELECT COUNT(*) FROM smm_services")->fetchColumn();
            $pdo->exec("DELETE FROM smm_services");
            echo json_encode(['status' => '1', 'msg' => "All {$count} SMM services have been deleted."]);
        } catch (PDOException $e) {
            echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
        }
        break;

    default:
        echo json_encode(['status'=>'0','msg'=>'Unknown action']);
        break;
}
?>