<?php
// controllers/RootCauseController.php

/**
 * RootCauseController for Rehlko Customer Care application.
 * Manages CRUD operations for root cause entries linked to reports.
 * Only engineers assigned to a report can perform CRUD on its root causes.
 */
class RootCauseController {
    private $conn;
    private $rootCauseModel;
    private $reportModel; // To validate report_index and engineer assignment

    /**
     * Constructor for RootCauseController.
     *
     * @param mysqli $db The database connection object.
     */
    public function __construct($db) {
        $this->conn = $db;
        $this->rootCauseModel = new RootCause($db);
        $this->reportModel = new Report($db);
    }

    /**
     * Creates a new root cause for a report.
     * Only engineers assigned to the report can create.
     */
    public function readAllByReportIndex($reportIndex) {
        $currentUserRole = getCurrentUserRole();
        $currentUserId = getCurrentUserId();

        // Verify report existence and engineer authorization
        $report = $this->reportModel->readOneEngineer($reportIndex, 'index');
        if (!$report) {
            sendJsonResponse(['message' => 'Report not found.'], 404);
        }

        $authorized = false;
        if (in_array($currentUserRole, ['superadmin', 'admin'])) {
            $authorized = true;
        } else if ($currentUserRole === 'engineer' && $report['engineer_id'] == $currentUserId) {
             $authorized = true;
        } else if (in_array($currentUserRole, ['localcustomer', 'globalcustomer'])&& $report['customer_id'] == $currentUserId) { // Allow customer to view their reports' root causes
             $authorized = true;
        }


        if (!$authorized) {
            sendJsonResponse(['message' => 'Unauthorized to view root causes for this report.'], 403);
        }

        $stmt = $this->rootCauseModel->readAllByReportIndex($reportIndex);
        if ($stmt->num_rows > 0) {
            $rootCauses = [];
            while ($row = $stmt->fetch_assoc()) {
                $rootCauses[] = $row;
            }
            sendJsonResponse(['success' => true, 'message' => 'Root causes retrieved successfully.', 'data' => $rootCauses], 200);
        } else {
            sendJsonResponse(['success' => true, 'message' => 'No root causes found for this report.', 'data' => []], 200);
        }
    }
    
    public function create() {
        $currentUserRole = getCurrentUserRole();
        $currentUserId = getCurrentUserId();
        
        

        $data = json_decode(file_get_contents("php://input"), true); // Decode as associative array for consistent access

        // Use $_POST for text fields if multipart/form-data, otherwise $data from json
        $reportIndex = $_POST['report_index'] ?? ($data['report_index'] ?? null);
        $rootCauseTitle = $_POST['root_cause_title'] ?? ($data['root_cause_title'] ?? null);
        $mediaType = $_POST['media_type'] ?? ($data['media_type'] ?? null); // 'image' or 'video'
        

        if (empty($reportIndex) || empty($rootCauseTitle)) {
            sendJsonResponse(['message' => 'Missing required fields: report_index, root_cause_title.'], 400);
        }
        

        // Verify report existence and engineer authorization
        $report = $this->reportModel->readOneEngineer($reportIndex, 'index');
        if (!$report) {
            sendJsonResponse(['message' => 'Report not found.'], 404);
        }
        
        $authorized = false;
        if (in_array($currentUserRole, ['superadmin', 'admin'])) {
            $authorized = true;
        } else if($currentUserRole === 'engineer' && $report['engineer_id'] == $currentUserId) {
             $authorized = true;
        }
        

        if (!$authorized) {
            sendJsonResponse(['message' => 'Unauthorized. Only engineers can create root causes.'], 403);
        }
        $mediaPath = null;
        $mediaName = null;

        // Handle file uploads (for single or multiple images/video)
        if (!empty($_FILES)) {
            if (isset($_FILES['media']) && is_array($_FILES['media']['name'])) { // Multiple images
                // Handle multiple images if necessary, or just pick the first one
                $file = [
                    'name' => $_FILES['media']['name'][0],
                    'type' => $_FILES['media']['type'][0],
                    'tmp_name' => $_FILES['media']['tmp_name'][0],
                    'error' => $_FILES['media']['error'][0],
                    'size' => $_FILES['media']['size'][0],
                ];
            } elseif (isset($_FILES['media']) && !is_array($_FILES['media']['name'])) { // Single image
                 $file = $_FILES['media'];
            } elseif (isset($_FILES['media_video'])) { // Single video
                $file = $_FILES['media_video'];
                $mediaType = 'video'; // Ensure media_type is correctly set for video
            }

            if (isset($file) && $file['error'] == UPLOAD_ERR_OK) {
                $uploadResult = $this->rootCauseModel->uploadMedia($file, $reportIndex, $mediaType);
                if ($uploadResult) {
                    $mediaPath = $uploadResult['media_path'];
                    $mediaName = $uploadResult['media_name'];
                } else {
                    sendJsonResponse(['message' => 'Failed to upload media.'], 500);
                }
            }
        }

        $this->rootCauseModel->report_index = $reportIndex;
        $this->rootCauseModel->root_cause_title = $rootCauseTitle;
        $this->rootCauseModel->root_cause_media_type = $mediaType;
        $this->rootCauseModel->root_cause_media_path = $mediaPath;
        $this->rootCauseModel->root_cause_media_name = $mediaName;
        $this->rootCauseModel->created_user = $currentUserId;


        if ($this->rootCauseModel->create()) {
            sendJsonResponse(['success' => true, 'message' => 'Root cause created successfully.'], 200);
        } else {
            sendJsonResponse(['message' => 'Failed to create root cause.'], 500);
        }
    }
    
    public function update($id) {
        $currentUserRole = getCurrentUserRole();
        $currentUserId = getCurrentUserId();

        // Fetch the existing root cause to check authorization and current media
        $this->rootCauseModel->id = $id;
        $existingRootCause = $this->rootCauseModel->readOne();
        if (!$existingRootCause) {
            sendJsonResponse(['message' => 'Root cause not found.'], 404);
        }

        
        $authorized = false;
        if (in_array($currentUserRole, ['superadmin', 'admin'])) {
            $report = $this->reportModel->readOne($existingRootCause['report_index'], 'index');
            $authorized = true;
        } elseif($currentUserRole === 'engineer') {
            error_log("Haha U R ENG");
            $report = $this->reportModel->readOneEngineer($existingRootCause['report_index'], 'index');
            if($report['engineer_id'] == $currentUserId){
             $authorized = true;
            }
        }
        

        if (!$authorized) {
            sendJsonResponse(['message' => 'Unauthorized. Only superadmin,admin and engineers can update root causes.'], 403);
        }

        $data = json_decode(file_get_contents("php://input"), true); // Attempt to decode JSON for text fields first
        $isMultipart = strpos(apache_request_headers()['Content-Type'] ?? '', 'multipart/form-data') !== false;

        // Get data from $_POST for multipart requests, otherwise from $data
        $rootCauseTitle = $isMultipart ? ($_POST['root_cause_title'] ?? ($data['root_cause_title'] ?? null)) : ($data['root_cause_title'] ?? null);
        $mediaType = $isMultipart ? ($_POST['media_type'] ?? ($data['media_type'] ?? null)) : ($data['media_type'] ?? null);
        $clearMedia = $isMultipart ? ($_POST['clear_media'] ?? null) : ($data['clear_media'] ?? null);


        if (empty($rootCauseTitle)) {
            sendJsonResponse(['message' => 'Missing required fields: root_cause_title.'], 400);
        }

        $this->rootCauseModel->id = $id;
        $this->rootCauseModel->root_cause_title = $rootCauseTitle;
        $this->rootCauseModel->report_index = $existingRootCause['report_index']; // Keep existing report index

        $currentMediaPath = $existingRootCause['root_cause_media_path'];
        $currentMediaType = $existingRootCause['root_cause_media_type'];
        $currentMediaName = $existingRootCause['root_cause_media_name'];

        // Handle media update/removal
        if ($clearMedia && $clearMedia === '1') {
            // Explicitly clearing media
            if ($currentMediaPath && file_exists(__DIR__ . '/../public/' . $currentMediaPath)) {
                unlink(__DIR__ . '/../public/uploads/rootcause' . $currentMediaPath);
            }
            $this->rootCauseModel->root_cause_media_type = null;
            $this->rootCauseModel->root_cause_media_path = null;
            $this->rootCauseModel->root_cause_media_name = null;
        } else if (!empty($_FILES)) {
            // A new file is being uploaded, delete old one if exists
            if ($currentMediaPath && file_exists(__DIR__ . '/../public/' . $currentMediaPath)) {
                unlink(__DIR__ . '/../public/' . $currentMediaPath);
            }

            $file = null;
            if (isset($_FILES['media']) && is_array($_FILES['media']['name'])) { // Multiple images, taking first
                $file = [
                    'name' => $_FILES['media']['name'][0],
                    'type' => $_FILES['media']['type'][0],
                    'tmp_name' => $_FILES['media']['tmp_name'][0],
                    'error' => $_FILES['media']['error'][0],
                    'size' => $_FILES['media']['size'][0],
                ];
            } elseif (isset($_FILES['media']) && !is_array($_FILES['media']['name'])) { // Single image
                $file = $_FILES['media'];
            } elseif (isset($_FILES['media_video'])) { // Single video
                $file = $_FILES['media_video'];
                $mediaType = 'video';
            }

            if ($file && $file['error'] == UPLOAD_ERR_OK) {
                $uploadResult = $this->rootCauseModel->uploadMedia($file, $existingRootCause['report_index'], $mediaType);
                if ($uploadResult) {
                    $this->rootCauseModel->root_cause_media_type = $mediaType;
                    $this->rootCauseModel->root_cause_media_path = $uploadResult['media_path'];
                    $this->rootCauseModel->root_cause_media_name = $uploadResult['media_name'];
                } else {
                    sendJsonResponse(['message' => 'Failed to upload new media.'], 500);
                }
            } else {
                // No new file or upload error, keep existing media path
                $this->rootCauseModel->root_cause_media_type = $currentMediaType;
                $this->rootCauseModel->root_cause_media_path = $currentMediaPath;
                $this->rootCauseModel->root_cause_media_name = $currentMediaName;
            }
        } else {
            // No new file, not clearing, keep existing media path
            $this->rootCauseModel->root_cause_media_type = $currentMediaType;
            $this->rootCauseModel->root_cause_media_path = $currentMediaPath;
            $this->rootCauseModel->root_cause_media_name = $currentMediaName;
        }

        $this->rootCauseModel->modified_user = $currentUserId; // Assuming you have this field


        if ($this->rootCauseModel->update()) {
            sendJsonResponse(['success' => true, 'message' => 'Root cause updated successfully.'], 200);
        } else {
            sendJsonResponse(['message' => 'Failed to update root cause.'], 500);
        }
    }

    /**
     * Reads root cause entries for a given report index.
     * Access is based on report view permissions.
     *
     * @param string $reportIndex The report index to retrieve root causes for.
     */
    public function readByReportIndex($reportIndex) {
        $currentUserRole = getCurrentUserRole();
        if (!$currentUserRole) {
            sendJsonResponse(['message' => 'Authentication required.'], 401);
        }

        // Verify user authorization to view this report first
        $report = $this->reportModel->readOne($reportIndex, 'index');
        if (!$report) {
            sendJsonResponse(['message' => 'Report not found or unauthorized to view.'], 404); // readOne sends 403 if unauthorized
        }

        $rootCauses = $this->rootCauseModel->readByReportIndex($reportIndex);

        if ($rootCauses !== false) {
            sendJsonResponse($rootCauses);
        } else {
            sendJsonResponse(['message' => 'Failed to retrieve root causes.'], 500);
        }
    }

    /**
     * Updates an existing root cause.
     * Only the engineer assigned to the report can update.
     *
     * @param int $id The ID of the root cause to update.
     */
    

    /**
     * Deletes a root cause.
     * Only the engineer assigned to the report can delete, or superadmin/admin.
     *
     * @param int $id The ID of the root cause to delete.
     */
    public function delete($id) {
        $currentUserRole = getCurrentUserRole();
        $currentUserId = getCurrentUserId();

        // Fetch the root cause to get its report_index
        $this->rootCauseModel->id = $id;
        $rootCause = $this->rootCauseModel->readOne();
        if (!$rootCause) {
            sendJsonResponse(['message' => 'Root cause not found.'], 404);
        }

        // Authorize: Superadmin/Admin or the assigned engineer
        $authorized = false;
        if (in_array($currentUserRole, ['superadmin', 'admin'])) {
            $authorized = true;
        } else {
            $report = $this->reportModel->readOne($rootCause['report_index'], 'index');
            if ($report && $report['engineer_id'] == $currentUserId) {
                 $authorized = true;
            }
        }

        if (!$authorized) {
            sendJsonResponse(['message' => 'Unauthorized to delete this root cause.'], 403);
        }

        if ($this->rootCauseModel->delete()) {
            sendJsonResponse(['success' => true,'message' => 'Root cause deleted successfully.'], 200);
        } else {
            sendJsonResponse(['message' => 'Failed to delete root cause.'], 500);
        }
    }
}
?>
