<?php

namespace App\Controllers;

use App\Controllers\Base\IndustrialVisitController as BaseIndustrialVisitController;

class IndustrialVisitController extends BaseIndustrialVisitController
{
    /**
     * Create new industrial visit with multiple attachments
     * POST /industrial-visits
     */
    public function store()
    {
        $validated = $this->validate([
            'company_id' => 'required|integer',
            'teacher_in_charge_id' => 'integer',
            'class_name' => 'required|string|max:50',
            'visit_date' => 'required',
            'documentation_path' => 'string',
            'notes' => 'string',
            '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;
        }

        // Handle multiple file uploads for Industrial Visit
        $uploadedFiles = [];
        $files = $_FILES['files'] ?? $_FILES['file'] ?? null;

        if ($files) {
            if (isset($files['name']) && is_array($files['name'])) {
                // Multiple files
                for ($i = 0; $i < count($files['name']); $i++) {
                    if ($files['error'][$i] === UPLOAD_ERR_OK) {
                        try {
                            $singleFile = [
                                'name' => $files['name'][$i],
                                'type' => $files['type'][$i],
                                'tmp_name' => $files['tmp_name'][$i],
                                'error' => $files['error'][$i],
                                'size' => $files['size'][$i],
                            ];
                            $path = \Wibiesana\Padi\Core\File::upload($singleFile, 'industrial_visits', ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx']);
                            $uploadedFiles[] = 'uploads/' . $path;
                        } catch (\Exception $e) {
                            throw new \Exception("File upload failed at index {$i}: " . $e->getMessage(), 400);
                        }
                    }
                }
            } elseif (isset($files['error']) && $files['error'] === UPLOAD_ERR_OK) {
                // Single file
                try {
                    $path = \Wibiesana\Padi\Core\File::upload($files, 'industrial_visits', ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx']);
                    $uploadedFiles[] = 'uploads/' . $path;
                } catch (\Exception $e) {
                    throw new \Exception("File upload failed: " . $e->getMessage(), 400);
                }
            }
        }

        if (!empty($uploadedFiles)) {
            $validated['documentation_path'] = json_encode($uploadedFiles);
        }

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

    /**
     * Update industrial visit with multiple attachments
     * PUT/POST /industrial-visits/update
     */
    public function update()
    {
        $id = $this->request->param('id') ?: $this->request->input('id');
        $visit = $this->model->find($id);
        
        if (!$visit) {
            throw new \Exception('Industrial Visit not found', 404);
        }
        
        $validated = $this->validate([
            'company_id' => 'required|integer',
            'teacher_in_charge_id' => 'integer',
            'class_name' => 'required|string|max:50',
            'visit_date' => 'required',
            'documentation_path' => 'string',
            'notes' => 'string',
            '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;
        }

        // Handle multiple file uploads
        $newUploadedFiles = [];
        $files = $_FILES['files'] ?? $_FILES['file'] ?? null;

        if ($files) {
            if (isset($files['name']) && is_array($files['name'])) {
                // Multiple files
                for ($i = 0; $i < count($files['name']); $i++) {
                    if ($files['error'][$i] === UPLOAD_ERR_OK) {
                        try {
                            $singleFile = [
                                'name' => $files['name'][$i],
                                'type' => $files['type'][$i],
                                'tmp_name' => $files['tmp_name'][$i],
                                'error' => $files['error'][$i],
                                'size' => $files['size'][$i],
                            ];
                            $path = \Wibiesana\Padi\Core\File::upload($singleFile, 'industrial_visits', ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx']);
                            $newUploadedFiles[] = 'uploads/' . $path;
                        } catch (\Exception $e) {
                            throw new \Exception("File upload failed at index {$i}: " . $e->getMessage(), 400);
                        }
                    }
                }
            } elseif (isset($files['error']) && $files['error'] === UPLOAD_ERR_OK) {
                // Single file
                try {
                    $path = \Wibiesana\Padi\Core\File::upload($files, 'industrial_visits', ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx']);
                    $newUploadedFiles[] = 'uploads/' . $path;
                } catch (\Exception $e) {
                    throw new \Exception("File upload failed: " . $e->getMessage(), 400);
                }
            }
        }

        // Selective Deletion Logic
        $existingFilesInput = $this->request->input('existing_files');
        $filesToKeep = [];

        if ($existingFilesInput !== null) {
            $filesToKeep = json_decode($existingFilesInput, true);
            if (!is_array($filesToKeep)) {
                $filesToKeep = !empty($existingFilesInput) ? explode(',', $existingFilesInput) : [];
            }

            // Clean up files that are NOT in the keep list
            $oldFilesStr = $visit['documentation_path'] ?? '';
            $oldFiles = json_decode($oldFilesStr, true);
            if (!is_array($oldFiles)) $oldFiles = !empty($oldFilesStr) ? [$oldFilesStr] : [];

            foreach ($oldFiles as $oldFile) {
                if (!in_array($oldFile, $filesToKeep)) {
                    $cleanPath = str_replace('uploads/', '', $oldFile);
                    \Wibiesana\Padi\Core\File::delete($cleanPath);
                }
            }
        } else {
            // Standard fallback behavior
            if (!empty($newUploadedFiles)) {
                if (!empty($visit['documentation_path'])) {
                    $oldFiles = json_decode($visit['documentation_path'], true);
                    if (!is_array($oldFiles)) $oldFiles = [$visit['documentation_path']];
                    foreach ($oldFiles as $oldFile) {
                        $cleanPath = str_replace('uploads/', '', $oldFile);
                        \Wibiesana\Padi\Core\File::delete($cleanPath);
                    }
                }
                $filesToKeep = [];
            } else {
                $oldFilesStr = $visit['documentation_path'] ?? '';
                $filesToKeep = json_decode($oldFilesStr, true);
                if (!is_array($filesToKeep)) $filesToKeep = !empty($oldFilesStr) ? [$oldFilesStr] : [];
            }
        }

        // Final Merge
        $finalFileList = array_merge($filesToKeep, $newUploadedFiles);
        if (!empty($finalFileList)) {
            $validated['documentation_path'] = json_encode($finalFileList);
        } else {
            $validated['documentation_path'] = null;
        }

        try {
            $this->model->update($id, $validated);
            $this->model->with(['company:id,name', 'teacherInCharge:id,name']);
            return \App\Resources\IndustrialVisitResource::make($this->model->find($id));
        } catch (\PDOException $e) {
            $this->databaseError('Failed to update industrial visit', $e);
        }
    }
}