<?php

namespace App\Http\Controllers\Owner;

use App\Http\Controllers\Controller;
use App\Models\BookingItem;
use App\Models\Payout;
use App\Models\ProofSubmission;
use App\Models\TrustScore;
use App\Models\Placement;
use Illuminate\Http\Request;

class OwnerController extends Controller
{
    // ============================================================
    // Dashboard
    // ============================================================
    public function dashboard()
    {
        $owner = auth()->user()->mediaOwner;

        abort_if(!$owner, 403, 'No media owner profile found.');

        // Active booking items
        $activeItems = BookingItem::forOwner($owner->id)
            ->whereIn('status', ['confirmed', 'creative_pending',
                                 'creative_approved', 'active'])
            ->with(['booking.user', 'placement'])
            ->latest()
            ->get();

        // Proof tasks due
        $proofTasks = BookingItem::forOwner($owner->id)
            ->where('status', 'proof_pending')
            ->with(['booking.user', 'placement'])
            ->orderBy('proof_due_at')
            ->get();

        // Overdue proofs
        $overdueProofs = $proofTasks->filter(fn($i) => $i->isProofOverdue());

        // Recent completed
        $recentCompleted = BookingItem::forOwner($owner->id)
            ->where('status', 'completed')
            ->with(['booking.user', 'placement', 'payout'])
            ->latest()
            ->limit(5)
            ->get();

        // Payouts
        $pendingPayouts = Payout::forOwner($owner->id)
            ->whereIn('status', ['pending', 'approved'])
            ->with('bookingItem.placement')
            ->get();

        $heldPayouts = Payout::forOwner($owner->id)
            ->held()
            ->with(['bookingItem.placement', 'activeHold'])
            ->get();

        // Trust score
        $trustScore = TrustScore::where('media_owner_id', $owner->id)
            ->whereNull('placement_id')
            ->first();

        // Stats
        $stats = [
            'total_placements'  => Placement::where('media_owner_id', $owner->id)->count(),
            'active_bookings'   => $activeItems->count(),
            'proof_tasks'       => $proofTasks->count(),
            'overdue_proofs'    => $overdueProofs->count(),
            'pending_payout'    => Payout::forOwner($owner->id)
                                    ->whereIn('status', ['pending','approved'])
                                    ->sum('net_amount'),
            'held_payout'       => Payout::forOwner($owner->id)
                                    ->held()->sum('net_amount'),
            'trust_score'       => $owner->trust_score,
            'sla_compliance'    => $owner->sla_compliance_rate,
        ];

        return view('owner.dashboard', compact(
            'owner',
            'activeItems',
            'proofTasks',
            'overdueProofs',
            'recentCompleted',
            'pendingPayouts',
            'heldPayouts',
            'trustScore',
            'stats'
        ));
    }

    // ============================================================
    // Placements list
    // ============================================================
    public function placements()
    {
        $owner = auth()->user()->mediaOwner;
        abort_if(!$owner, 403);

        $placements = Placement::where('media_owner_id', $owner->id)
            ->with(['pricingPolicy', 'trustScore'])
            ->latest()
            ->paginate(12);

        return view('owner.placements', compact('owner', 'placements'));
    }

    // ============================================================
    // Payout ledger
    // ============================================================
    public function payouts()
    {
        $owner = auth()->user()->mediaOwner;
        abort_if(!$owner, 403);

        $payouts = Payout::forOwner($owner->id)
            ->with(['bookingItem.placement', 'bookingItem.booking', 'holds'])
            ->latest()
            ->paginate(15);

        $summary = [
            'total_paid'    => Payout::forOwner($owner->id)->paid()->sum('net_amount'),
            'pending'       => Payout::forOwner($owner->id)
                                ->whereIn('status',['pending','approved'])
                                ->sum('net_amount'),
            'held'          => Payout::forOwner($owner->id)->held()->sum('net_amount'),
        ];

        return view('owner.payouts', compact('owner', 'payouts', 'summary'));
    }
}