<?php
require_once __DIR__.'/../app/bootstrap.php';
use App\Core\Auth;use App\Core\Database;use App\Core\Response;
Auth::requireRole(['affiliate','admin']);if($_SERVER['REQUEST_METHOD']!=='POST'||!verify_csrf())Response::json(['ok'=>false,'message'=>'Invalid request.'],419);$d=request_data();$pid=(int)($d['product_id']??0);$member=Database::safeFetchOne('SELECT * FROM affiliate_members WHERE user_id=? AND status="active" LIMIT 1',[Auth::id()]);if(!$member)Response::json(['ok'=>false,'message'=>'Affiliate profile is not active.'],422);$action=(string)($d['action']??'add');
if($action==='remove'){Database::safeExecute('DELETE FROM affiliate_products WHERE affiliate_member_id=? AND product_id=?',[$member['id'],$pid]);Response::json(['ok'=>true,'message'=>'Product removed.']);}
$plan=Database::safeFetchOne('SELECT ap.* FROM affiliate_member_plans amp JOIN affiliate_plans ap ON ap.id=amp.plan_id WHERE amp.affiliate_member_id=? AND amp.status="active" AND (amp.ends_at IS NULL OR amp.ends_at>=CURDATE()) ORDER BY amp.id DESC LIMIT 1',[$member['id']]);$limit=(int)($plan['product_limit']??25);if(db_count('affiliate_products','affiliate_member_id=?',[$member['id']])>=$limit)Response::json(['ok'=>false,'message'=>'Your selected-product limit is '.$limit.'.'],422);if(!Database::safeFetchOne('SELECT id FROM products WHERE id=? AND status="published"',[$pid]))Response::json(['ok'=>false,'message'=>'Product unavailable.'],404);Database::safeExecute('INSERT INTO affiliate_products (affiliate_member_id,product_id,sort_order,created_at) SELECT ?,?,?,NOW() WHERE NOT EXISTS (SELECT 1 FROM affiliate_products WHERE affiliate_member_id=? AND product_id=?)',[$member['id'],$pid,0,$member['id'],$pid]);Response::json(['ok'=>true,'message'=>'Product added to your affiliate shop.']);
