<?php

namespace App\Http\Controllers;

use App\Models\MarketingRequest;
use App\Services\RequestWorkflowService;
use Illuminate\Http\Request;

class WorkflowController extends Controller
{
    public function startWork(MarketingRequest $request)
    {
        $this->authorize('startWork', $request);
        $user = auth()->user();

        RequestWorkflowService::startWork($request, $user);

        return back()->with('success', 'Work started! Status changed to In Progress.');
    }

    public function uploadProof(Request $httpRequest, MarketingRequest $request)
    {
        $this->authorize('uploadProof', $request);

        $httpRequest->validate([
            'proof_file' => ['required', 'file', 'mimes:jpg,jpeg,png,pdf', 'max:30720'], // Max 30MB
        ], [
            'proof_file.required' => 'Please select a proof file to upload.',
            'proof_file.mimes' => 'Allowed proof formats: JPG, JPEG, PNG, PDF.',
            'proof_file.max' => 'Proof file size cannot exceed 30MB.',
        ]);

        $user = auth()->user();
        $file = $httpRequest->file('proof_file');

        RequestWorkflowService::uploadProof($request, $file, $user);

        return back()->with('success', 'Proof uploaded successfully! Request sent for Harcourts Admin review.');
    }

    public function requestChanges(Request $httpRequest, MarketingRequest $request)
    {
        $this->authorize('requestChanges', $request);

        $httpRequest->validate([
            'feedback' => ['required', 'string', 'min:3', 'max:2000'],
        ], [
            'feedback.required' => 'Feedback cannot be empty when requesting changes.',
            'feedback.min' => 'Please provide a clear description of the requested changes (at least 3 characters).',
        ]);

        $user = auth()->user();
        $feedback = $httpRequest->input('feedback');

        RequestWorkflowService::requestChanges($request, $feedback, $user);

        return back()->with('success', 'Revision requested! Designer has been notified.');
    }

    public function startRevision(MarketingRequest $request)
    {
        $this->authorize('startRevision', $request);
        $user = auth()->user();

        RequestWorkflowService::startRevision($request, $user);

        return back()->with('success', 'Revision work started! Status updated to In Revision.');
    }

    public function approve(MarketingRequest $request)
    {
        $this->authorize('approve', $request);
        $user = auth()->user();

        RequestWorkflowService::approveDesign($request, $user);

        return back()->with('success', 'Design approved successfully!');
    }

    public function complete(MarketingRequest $request)
    {
        $this->authorize('complete', $request);
        $user = auth()->user();

        RequestWorkflowService::completeRequest($request, $user);

        return back()->with('success', 'Request marked as completed!');
    }
}
