<?php
require_once __DIR__.'/../includes/functions.php';
header('Content-Type: application/json');

try {
    mj_trust_bundle_ensure_schema();
    $u = current_user();
    if (!$u) { throw new Exception('Please login to save this item.'); }

    $type = strtolower(trim((string)($_POST['type'] ?? 'listing')));
    $id = (int)($_POST['id'] ?? 0);
    $action = strtolower(trim((string)($_POST['action'] ?? 'toggle')));
    if ($id <= 0) { throw new Exception('Invalid item.'); }

    if ($type === 'company') {
        $exists = one('SELECT id FROM mj_saved_companies WHERE user_id=? AND company_id=? LIMIT 1', [(int)$u['id'], $id]);
        if ($action === 'remove' || ($action === 'toggle' && $exists)) {
            q('DELETE FROM mj_saved_companies WHERE user_id=? AND company_id=?', [(int)$u['id'], $id]);
            echo json_encode(['ok'=>true,'saved'=>false,'message'=>'Company removed from saved items.']);
            exit;
        }
        if (!$exists) {
            q('INSERT IGNORE INTO mj_saved_companies(user_id,company_id,created_at) VALUES(?,?,NOW())', [(int)$u['id'], $id]);
        }
        echo json_encode(['ok'=>true,'saved'=>true,'message'=>'Company saved.']);
        exit;
    }

    $exists = one('SELECT id FROM mj_saved_listings WHERE user_id=? AND listing_id=? LIMIT 1', [(int)$u['id'], $id]);
    if ($action === 'remove' || ($action === 'toggle' && $exists)) {
        q('DELETE FROM mj_saved_listings WHERE user_id=? AND listing_id=?', [(int)$u['id'], $id]);
        try { q('UPDATE mj_listings SET save_count=GREATEST(COALESCE(save_count,0)-1,0) WHERE id=?', [$id]); } catch (Throwable $e) {}
        echo json_encode(['ok'=>true,'saved'=>false,'message'=>'Listing removed from saved items.']);
        exit;
    }
    if (!$exists) {
        q('INSERT IGNORE INTO mj_saved_listings(user_id,listing_id,created_at) VALUES(?,?,NOW())', [(int)$u['id'], $id]);
        try { q('UPDATE mj_listings SET save_count=COALESCE(save_count,0)+1 WHERE id=?', [$id]); } catch (Throwable $e) {}
    }
    echo json_encode(['ok'=>true,'saved'=>true,'message'=>'Listing saved.']);
} catch (Throwable $e) {
    echo json_encode(['ok'=>false,'error'=>$e->getMessage()]);
}
