<?php
require_once '../core/bootstrap.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'create';
    $user_id = $_SESSION['user_id'];
    $walletModel = new Wallet();
    $sponsorModel = new Sponsorship();

    if ($action === 'setup_business') {
        $business_name = trim($_POST['business_name']);
        $business_description = trim($_POST['business_description']);
        $current_logo = $_POST['current_logo'] ?? '';
        $logo_path = $current_logo;

        // Handle logo upload
        if (isset($_FILES['business_logo']) && $_FILES['business_logo']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = '../uploads/sponsors/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
            
            $finfo = new finfo(FILEINFO_MIME_TYPE);
            $mime = $finfo->file($_FILES['business_logo']['tmp_name']);
            $allowed_mimes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];

            if (in_array($mime, $allowed_mimes)) {
                $file_ext = strtolower(pathinfo($_FILES['business_logo']['name'], PATHINFO_EXTENSION));
                $filename = 'logo_' . $user_id . '_' . time() . '.' . $file_ext;
                $target = $upload_dir . $filename;
                
                if (move_uploaded_file($_FILES['business_logo']['tmp_name'], $target)) {
                    $logo_path = URL_ROOT . '/uploads/sponsors/' . $filename;
                }
            }
        }

        $data = [
            'user_id' => $user_id,
            'business_name' => $business_name,
            'business_description' => $business_description,
            'business_logo' => $logo_path
        ];

        if ($sponsorModel->createOrUpdateSponsorProfile($data)) {
            header('Location: sponsor_dashboard.php?status=success&msg=Business profile updated.');
        } else {
            header('Location: sponsor_dashboard.php?status=error&msg=Failed to update profile.');
        }
    } elseif ($action === 'create') {
        // Fetch sponsor profile to get the logo
        $sponsor_profile = $sponsorModel->getSponsorProfileByUserId($user_id);
        if (!$sponsor_profile || empty($sponsor_profile->business_logo)) {
            header('Location: sponsor_dashboard.php?status=error&msg=Please set up your business profile with a logo first.');
            exit();
        }

        // Verify the logo file actually exists on the server
        $logo_fs_path = str_replace(URL_ROOT . '/', '../', $sponsor_profile->business_logo);
        if (!file_exists($logo_fs_path)) {
            header('Location: sponsor_dashboard.php?status=error&msg=Business logo file missing. Please re-upload in profile.');
            exit();
        }

        $package_id = $_POST['package_id'];
        $price = $_POST['price'];
        $entity_id = $_POST['entity_id'] ?? null;
        
        // Use business logo as ad content
        $ad_content = $sponsor_profile->business_logo;
        $ad_type = 'image'; // Sponsorships are always images/logos

        $wallet = $walletModel->getOrCreateWallet('user', $user_id);

        if ($wallet->balance < $price) {
            header('Location: sponsor_dashboard.php?status=error&msg=Insufficient funds');
            exit();
        }

        // Get package duration
        $pkg = $sponsorModel->getPackageById($package_id);
        $duration = $pkg->duration_days ?? 30;
        $end_date = date('Y-m-d H:i:s', strtotime("+$duration days"));

        // Deduct funds
        if ($walletModel->withdraw($wallet->id, $price, "Sponsorship: " . $pkg->name, "SPON-" . uniqid())) {
            // Create Campaign
            $data = [
                'user_id' => $user_id,
                'package_id' => $package_id,
                'entity_id' => $entity_id,
                'ad_content' => $ad_content,
                'ad_type' => $ad_type,
                'aggression' => 1, // Not relevant for sponsorships, but DB requires it.
                'end_date' => $end_date
            ];
            $sponsorModel->createCampaign($data);
            header('Location: sponsor_dashboard.php?status=success&msg=Campaign created successfully');
        } else {
            header('Location: sponsor_dashboard.php?status=error&msg=Transaction failed');
        }
    } elseif ($action === 'create_custom') {
        $name = $_POST['name'];
        $payment_model = $_POST['payment_model'];
        $total_budget = (float)$_POST['total_budget'];
        $daily_budget = (float)$_POST['daily_budget'];
        $target_url = $_POST['target_url'] ?? null;
        $contact_number = $_POST['contact_number'] ?? null;

        if ($daily_budget > $total_budget) {
            header('Location: sponsor_dashboard.php?status=error&msg=Daily budget cannot exceed total budget');
            exit();
        }

        if ($target_url && !filter_var($target_url, FILTER_VALIDATE_URL)) {
            header('Location: sponsor_dashboard.php?status=error&msg=Invalid Target URL');
            exit();
        }

        // Handle File Upload
        $ad_content = '';
        $ad_type = 'image';
        
        if (isset($_FILES['ad_media']) && $_FILES['ad_media']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = '../uploads/ads/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
            
            $finfo = new finfo(FILEINFO_MIME_TYPE);
            $mime = $finfo->file($_FILES['ad_media']['tmp_name']);
            $allowed_mimes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'video/mp4', 'video/webm'];

            if (in_array($mime, $allowed_mimes)) {
                $ext = pathinfo($_FILES['ad_media']['name'], PATHINFO_EXTENSION);
                $filename = 'ad_' . uniqid() . '.' . $ext;
                $target = $upload_dir . $filename;
                
                if (move_uploaded_file($_FILES['ad_media']['tmp_name'], $target)) {
                    $ad_content = URL_ROOT . '/uploads/ads/' . $filename;
                    if (strpos($mime, 'video') !== false) $ad_type = 'video';
                }
            }
        }

        if (empty($ad_content)) {
            header('Location: sponsor_dashboard.php?status=error&msg=Media upload failed');
            exit();
        }

        $wallet = $walletModel->getOrCreateWallet('user', $user_id);
        if ($wallet->balance < $total_budget) {
            header('Location: sponsor_dashboard.php?status=error&msg=Insufficient funds for budget');
            exit();
        }

        // Deduct full budget upfront (Prepaid)
        if ($walletModel->withdraw($wallet->id, $total_budget, "Ad Campaign Budget: " . $name, "AD-" . uniqid())) {
            $data = [
                'user_id' => $user_id,
                'name' => $name,
                'ad_content' => $ad_content,
                'ad_type' => $ad_type,
                'payment_model' => $payment_model,
                'total_budget' => $total_budget,
                'daily_budget' => $daily_budget,
                'target_url' => $target_url,
                'contact_number' => $contact_number,
                'package_id' => 0 // 0 for custom/general ad
            ];
            $sponsorModel->createCustomCampaign($data);
            header('Location: sponsor_dashboard.php?status=success&msg=Campaign launched successfully');
        } else {
            header('Location: sponsor_dashboard.php?status=error&msg=Transaction failed');
        }
    } elseif ($action === 'update') {
        $campaign_id = filter_input(INPUT_POST, 'campaign_id', FILTER_VALIDATE_INT);
        $ad_content = $_POST['ad_content'] ?? '';
        $ad_type = $_POST['ad_type'];
        $aggression = $_POST['aggression'] ?? 1;

        // Verify ownership
        $campaign = $sponsorModel->getCampaignById($campaign_id);
        if (!$campaign || $campaign->user_id != $user_id) {
            header('Location: sponsor_dashboard.php?status=error&msg=Invalid campaign');
            exit();
        }

        // Handle new file upload if present
        if (isset($_FILES['ad_media']) && $_FILES['ad_media']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = '../uploads/ads/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
            
            $finfo = new finfo(FILEINFO_MIME_TYPE);
            $mime = $finfo->file($_FILES['ad_media']['tmp_name']);
            $allowed_mimes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'video/mp4', 'video/webm'];

            if (in_array($mime, $allowed_mimes)) {
                $ext = pathinfo($_FILES['ad_media']['name'], PATHINFO_EXTENSION);
                $filename = 'ad_' . uniqid() . '.' . $ext;
                $target = $upload_dir . $filename;
                
                if (move_uploaded_file($_FILES['ad_media']['tmp_name'], $target)) {
                    $ad_content = URL_ROOT . '/uploads/ads/' . $filename;
                    $ad_type = (strpos($mime, 'video') !== false) ? 'video' : 'image';
                }
            }
        }

        $data = [
            'ad_content' => $ad_content,
            'ad_type' => $ad_type,
            'aggression' => $aggression
        ];

        if ($sponsorModel->updateCampaign($campaign_id, $data)) {
            header('Location: sponsor_dashboard.php?status=success&msg=Campaign updated successfully');
        } else {
            header('Location: sponsor_dashboard.php?status=error&msg=Failed to update campaign');
        }
    } elseif ($action === 'pause') {
        $campaign_id = filter_input(INPUT_POST, 'campaign_id', FILTER_VALIDATE_INT);
        if ($sponsorModel->updateCampaignStatusByUser($campaign_id, $user_id, 'paused')) {
             header('Location: sponsor_dashboard.php?status=success&msg=Campaign paused');
        } else {
             header('Location: sponsor_dashboard.php?status=error&msg=Failed to pause campaign');
        }
    } elseif ($action === 'resume') {
        $campaign_id = filter_input(INPUT_POST, 'campaign_id', FILTER_VALIDATE_INT);
        if ($sponsorModel->updateCampaignStatusByUser($campaign_id, $user_id, 'active')) {
             header('Location: sponsor_dashboard.php?status=success&msg=Campaign resumed');
        } else {
             header('Location: sponsor_dashboard.php?status=error&msg=Failed to resume campaign');
        }
    } elseif ($action === 'extend') {
        $campaign_id = filter_input(INPUT_POST, 'campaign_id', FILTER_VALIDATE_INT);
        $days = filter_input(INPUT_POST, 'days', FILTER_VALIDATE_INT);

        if (!$campaign_id || !$days || $days < 1) {
             header('Location: sponsor_dashboard.php?status=error&msg=Invalid extension parameters');
             exit();
        }

        $campaign = $sponsorModel->getCampaignById($campaign_id);
        if (!$campaign || $campaign->user_id != $user_id) {
             header('Location: sponsor_dashboard.php?status=error&msg=Invalid campaign');
             exit();
        }

        $package = $sponsorModel->getPackageById($campaign->package_id);
        $duration = ($package->duration_days > 0) ? $package->duration_days : 30;
        $daily_rate = $package->price / $duration;
        $cost = $daily_rate * $days;

        $wallet = $walletModel->getOrCreateWallet('user', $user_id);
        if ($wallet->balance < $cost) {
             header('Location: sponsor_dashboard.php?status=error&msg=Insufficient funds');
             exit();
        }

        if ($walletModel->withdraw($wallet->id, $cost, "Campaign Extension: " . $package->name . " (+{$days} days)", "EXT-" . uniqid())) {
            $sponsorModel->extendCampaign($campaign_id, $days);
            header('Location: sponsor_dashboard.php?status=success&msg=Campaign extended successfully');
        } else {
            header('Location: sponsor_dashboard.php?status=error&msg=Transaction failed');
        }
    }
    exit();
}
header('Location: sponsor_dashboard.php');