<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;

class LegalAgreementController extends Controller
{
    /**
     * Upload a new legal agreement
     */
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'user_id' => 'required|exists:users,id',
            'agreement_file' => 'required|file|mimes:pdf,doc,docx|max:10240',
            'uploaded_by' => 'required|in:marketing_officer,user',
        ]);

        try {
            $userId = $request->user_id;
            $uploadedBy = $request->uploaded_by;
            
            // Store the file
            $file = $request->file('agreement_file');
            $filePath = $file->store('legal_agreements', 'public');
            
            // Get marketing officer ID if uploaded by marketing officer
            $marketingOfficerId = null;
            if ($uploadedBy === 'marketing_officer') {
                $marketingOfficerId = auth()->id();
            }
            
            // Create legal agreement
            $agreementId = DB::table('legal_agreements')->insertGetId([
                'user_id' => $userId,
                'marketing_officer_id' => $marketingOfficerId,
                'original_file_path' => $filePath,
                'status' => 'pending',
                'created_at' => now(),
                'updated_at' => now(),
            ]);
            
            Log::info('Legal agreement uploaded', [
                'agreement_id' => $agreementId,
                'user_id' => $userId,
                'uploaded_by' => $uploadedBy,
                'file_path' => $filePath
            ]);
            
            return response()->json([
                'success' => true,
                'message' => 'Legal agreement uploaded successfully',
                'agreement_id' => $agreementId,
            ], 201);
            
        } catch (\Exception $e) {
            Log::error('Failed to upload legal agreement', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to upload legal agreement',
            ], 500);
        }
    }
    
    /**
     * Get legal agreements for a specific user
     */
    public function getUserAgreements($userId): JsonResponse
    {
        try {
            $agreements = DB::table('legal_agreements')
                ->where('user_id', $userId)
                ->orderBy('created_at', 'desc')
                ->get();
            
            return response()->json([
                'success' => true,
                'data' => $agreements,
            ]);
            
        } catch (\Exception $e) {
            Log::error('Failed to fetch legal agreements', [
                'user_id' => $userId,
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch legal agreements',
            ], 500);
        }
    }
    
    /**
     * Upload signed agreement by user
     */
    public function uploadSigned(Request $request, $agreementId): JsonResponse
    {
        $request->validate([
            'signed_file' => 'required|file|mimes:pdf,doc,docx|max:10240',
        ]);
        
        try {
            $agreement = DB::table('legal_agreements')->find($agreementId);
            
            if (!$agreement) {
                return response()->json([
                    'success' => false,
                    'message' => 'Agreement not found',
                ], 404);
            }
            
            // Store the signed file
            $file = $request->file('signed_file');
            $filePath = $file->store('legal_agreements/signed', 'public');
            
            // Update agreement
            DB::table('legal_agreements')
                ->where('id', $agreementId)
                ->update([
                    'signed_file_path' => $filePath,
                    'status' => 'signed',
                    'signed_at' => now(),
                    'updated_at' => now(),
                ]);
            
            Log::info('Signed legal agreement uploaded', [
                'agreement_id' => $agreementId,
                'user_id' => $agreement->user_id,
                'file_path' => $filePath
            ]);
            
            return response()->json([
                'success' => true,
                'message' => 'Signed agreement uploaded successfully',
            ]);
            
        } catch (\Exception $e) {
            Log::error('Failed to upload signed agreement', [
                'agreement_id' => $agreementId,
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to upload signed agreement',
            ], 500);
        }
    }
    
    /**
     * Delete a legal agreement
     */
    public function destroy($agreementId): JsonResponse
    {
        try {
            $agreement = DB::table('legal_agreements')->find($agreementId);
            
            if (!$agreement) {
                return response()->json([
                    'success' => false,
                    'message' => 'Agreement not found',
                ], 404);
            }
            
            // Delete files from storage
            if ($agreement->original_file_path) {
                Storage::disk('public')->delete($agreement->original_file_path);
            }
            if ($agreement->signed_file_path) {
                Storage::disk('public')->delete($agreement->signed_file_path);
            }
            
            // Delete record
            DB::table('legal_agreements')->where('id', $agreementId)->delete();
            
            Log::info('Legal agreement deleted', ['agreement_id' => $agreementId]);
            
            return response()->json([
                'success' => true,
                'message' => 'Agreement deleted successfully',
            ]);
            
        } catch (\Exception $e) {
            Log::error('Failed to delete legal agreement', [
                'agreement_id' => $agreementId,
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete agreement',
            ], 500);
        }
    }
}
