<?php

namespace App\Controllers;

use App\Controllers\Base\MouController as BaseMouController;

class MouController extends BaseMouController
{
    /**
     * Create new mou with file upload
     * POST /mous
     */
    public function store()
    {
        $validated = $this->validate([
            'company_id' => 'required|integer',
            'mou_number' => 'required|string|max:100',
            'agreement_date' => 'required',
            'start_date' => 'required',
            'expiry_date' => 'required',
            'status' => 'string|max:20',
            'file_path' => 'string|max:255',
            'created_by' => 'integer',
            'updated_by' => 'integer'
        ]);

        $user = $this->request->user;
        $userId = $user ? (is_array($user) ? ($user['id'] ?? $user['user_id'] ?? null) : ($user->id ?? $user->user_id ?? null)) : null;
        if ($userId) {
            $validated['created_by'] = $userId;
            $validated['updated_by'] = $userId;
        }

        $file = $_FILES['file'] ?? null;
        if ($file && $file['error'] === UPLOAD_ERR_OK) {
            try {
                $path = \Wibiesana\Padi\Core\File::upload($file, 'mous', ['pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png']);
                $validated['file_path'] = 'uploads/' . $path;
            } catch (\Exception $e) {
                throw new \Exception("File upload failed: " . $e->getMessage(), 400);
            }
        }

        try {
            $id = $this->model->create($validated);
            $this->model->with(['company:id,name']);
            $mou = $this->model->find($id);
            return $this->created(\App\Resources\MouResource::make($mou));
        } catch (\PDOException $e) {
            $this->databaseError('Failed to create mou', $e);
        }
    }

    /**
     * Update mou with file upload
     * PUT/POST /mous/update
     */
    public function update()
    {
        $id = $this->request->param('id') ?: $this->request->input('id');
        $mou = $this->model->find($id);
        
        if (!$mou) {
            throw new \Exception('Mou not found', 404);
        }
        
        $validated = $this->validate([
            'company_id' => 'required|integer',
            'mou_number' => 'required|string|max:100',
            'agreement_date' => 'required',
            'start_date' => 'required',
            'expiry_date' => 'required',
            'status' => 'string|max:20',
            'file_path' => 'string|max:255',
            'created_by' => 'integer',
            'updated_by' => 'integer'
        ]);
        
        $user = $this->request->user;
        $userId = $user ? (is_array($user) ? ($user['id'] ?? $user['user_id'] ?? null) : ($user->id ?? $user->user_id ?? null)) : null;
        if ($userId) {
            $validated['updated_by'] = $userId;
        }

        // Keep old file by default
        $validated['file_path'] = $mou['file_path'] ?? null;

        // If file_path is explicitly set to empty/null or requested deletion
        if ($this->request->input('delete_file') === 'true' || $this->request->input('delete_file') === true) {
            if (!empty($mou['file_path'])) {
                $cleanPath = str_replace('uploads/', '', $mou['file_path']);
                \Wibiesana\Padi\Core\File::delete($cleanPath);
            }
            $validated['file_path'] = null;
        }

        $file = $_FILES['file'] ?? null;
        if ($file && $file['error'] === UPLOAD_ERR_OK) {
            // Delete old file if exists
            if (!empty($mou['file_path'])) {
                $cleanPath = str_replace('uploads/', '', $mou['file_path']);
                \Wibiesana\Padi\Core\File::delete($cleanPath);
            }

            try {
                $path = \Wibiesana\Padi\Core\File::upload($file, 'mous', ['pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png']);
                $validated['file_path'] = 'uploads/' . $path;
            } catch (\Exception $e) {
                throw new \Exception("File upload failed: " . $e->getMessage(), 400);
            }
        }
        
        try {
            $this->model->update($id, $validated);
            $this->model->with(['company:id,name']);
            return \App\Resources\MouResource::make($this->model->find($id));
        } catch (\PDOException $e) {
            $this->databaseError('Failed to update mou', $e);
        }
    }
}