<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\Deal;
use App\Models\PipelineStage;
use App\Models\Contact;
use App\Models\User;

class PipelineController extends Controller {
    public function index(): void {
        $stages = PipelineStage::getStagesWithDeals();
        $summary = Deal::getPipelineSummary();
        $contacts = Contact::all('name ASC');
        $agents = User::getActiveAgents();

        $this->render('pipeline/index', [
            'stages'   => $stages,
            'summary'  => $summary,
            'contacts' => $contacts,
            'agents'   => $agents
        ]);
    }

    public function moveStage(): void {
        $dealId = (int)Request::post('deal_id');
        $stageId = (int)Request::post('stage_id');

        $deal = Deal::find($dealId);
        if (!$deal) {
            Response::error('Deal not found', 404);
        }

        $stage = PipelineStage::find($stageId);
        if (!$stage) {
            Response::error('Target stage not found', 404);
        }

        $status = 'open';
        $lowerStage = strtolower($stage['name']);
        if (str_contains($lowerStage, 'won')) {
            $status = 'won';
        } elseif (str_contains($lowerStage, 'lost')) {
            $status = 'lost';
        }

        Deal::update($dealId, [
            'stage_id' => $stageId,
            'status'   => $status
        ]);

        // Also sync contact stage
        Contact::update((int)$deal['contact_id'], ['stage_id' => $stageId]);

        Response::success(null, 'Deal stage updated successfully');
    }

    public function store(): void {
        $contactId = (int)Request::post('contact_id');
        $title = trim(Request::post('title', ''));
        $value = (float)Request::post('value', 0.00);
        $stageId = (int)Request::post('stage_id', 1);
        $assignedTo = Request::post('assigned_to') ? (int)Request::post('assigned_to') : null;
        $closingDate = Request::post('closing_date') ?: null;
        $notes = trim(Request::post('notes', ''));

        if (empty($contactId) || empty($title)) {
            Response::error('Contact and Deal Title are required.');
        }

        $dealId = Deal::create([
            'contact_id'   => $contactId,
            'stage_id'     => $stageId,
            'title'        => $title,
            'value'        => $value,
            'currency'     => 'USD',
            'closing_date' => $closingDate,
            'assigned_to'  => $assignedTo,
            'notes'        => $notes ?: null,
            'status'       => 'open',
            'created_at'   => date('Y-m-d H:i:s')
        ]);

        if (Request::isAjax()) {
            Response::success(Deal::getWithDetails($dealId), 'Deal created successfully');
        }
        Response::redirect('/pipeline');
    }

    public function update(int $id): void {
        $title = trim(Request::post('title', ''));
        $value = (float)Request::post('value', 0.00);
        $stageId = (int)Request::post('stage_id', 1);
        $assignedTo = Request::post('assigned_to') ? (int)Request::post('assigned_to') : null;
        $closingDate = Request::post('closing_date') ?: null;
        $notes = trim(Request::post('notes', ''));
        $status = Request::post('status', 'open');

        Deal::update($id, [
            'title'        => $title,
            'value'        => $value,
            'stage_id'     => $stageId,
            'assigned_to'  => $assignedTo,
            'closing_date' => $closingDate,
            'notes'        => $notes ?: null,
            'status'       => $status
        ]);

        if (Request::isAjax()) {
            Response::success(Deal::getWithDetails($id), 'Deal updated');
        }
        Response::redirect('/pipeline');
    }

    public function delete(int $id): void {
        Deal::delete($id);
        if (Request::isAjax()) {
            Response::success(null, 'Deal deleted');
        }
        Response::redirect('/pipeline');
    }
}
