<?php

namespace App\Http\Controllers;

use App\Models\Project;
use App\Models\ProgrammerPayment;
use Illuminate\Http\Request;

class ProgrammerDashboardController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('can:view own projects');
    }

    /**
     * Programmer Dashboard - Shows only their projects and earnings
     */
    public function index()
    {
        $programmer = auth()->user();

        // Get only projects assigned to this programmer
        $projects = Project::where('programmer_id', $programmer->id)
            ->with('customer')
            ->latest()
            ->get();

        // Calculate stats for this programmer
        $stats = [
            'total_projects' => $projects->count(),
            'active_projects' => $projects->whereIn('status', ['pending', 'in_progress'])->count(),
            'completed_projects' => $projects->where('status', 'completed')->count(),
            'total_earnings' => $projects->sum('commission_amount'),
            'total_paid' => ProgrammerPayment::where('programmer_id', $programmer->id)->sum('amount'),
        ];
        $stats['total_pending'] = $stats['total_earnings'] - $stats['total_paid'];

        return view('programmer.dashboard', compact('projects', 'stats', 'programmer'));
    }

    /**
     * Show a specific project (only if assigned to this programmer)
     */
    public function showProject(Project $project)
    {
        $programmer = auth()->user();

        // Ensure programmer can only view their own projects
        if ($project->programmer_id !== $programmer->id) {
            abort(403, 'You do not have access to this project.');
        }

        $project->load([
            'customer',
            'payments' => function ($q) use ($programmer) {
                $q->where('programmer_id', $programmer->id);
            }
        ]);

        return view('programmer.project_show', compact('project', 'programmer'));
    }

    /**
     * Show programmer's payment history
     */
    public function payments()
    {
        $programmer = auth()->user();

        $payments = ProgrammerPayment::where('programmer_id', $programmer->id)
            ->with('project')
            ->latest('date')
            ->paginate(20);

        $totals = [
            'total_earned' => Project::where('programmer_id', $programmer->id)->sum('commission_amount'),
            'total_paid' => ProgrammerPayment::where('programmer_id', $programmer->id)->sum('amount'),
        ];
        $totals['pending'] = $totals['total_earned'] - $totals['total_paid'];

        return view('programmer.payments', compact('payments', 'totals', 'programmer'));
    }

    /**
     * Update project progress (programmer can update their own projects)
     */
    public function updateProgress(Request $request, Project $project)
    {
        $programmer = auth()->user();

        if ($project->programmer_id !== $programmer->id) {
            abort(403, 'You do not have access to this project.');
        }

        $validated = $request->validate([
            'progress_percent' => 'required|integer|min:0|max:100',
            'notes' => 'nullable|string',
        ]);

        $project->update($validated);

        return back()->with('success', __('Project progress updated successfully.'));
    }
}
