<?php
// controllers/EffectiveActionController.php

/**
 * EffectiveActionController for Rehlko Customer Care application.
 * Manages CRUD operations for effective action entries linked to reports.
 */
class EffectiveActionController {
    private $conn;
    private $effectiveActionModel;
    private $reportModel; // To validate report_index and engineer assignment

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

    /**
     * Creates a new effective action for a report.
     */
    public function create() {
        $currentUserRole = getCurrentUserRole();
        $currentUserId = getCurrentUserId();
        $report_index = $_POST['report_index'] ?? null;
        $effective_action_title = $_POST['effective_action_title'] ?? null;
        
        // Validate required fields
        if (empty($report_index) || empty($effective_action_title)) {
            sendJsonResponse(['message' => 'Missing required fields: report_index, effective_action_title.'], 400);
            return;
        }
        
        $authorized = false;
        if (in_array($currentUserRole, ['superadmin', 'admin'])) {
            $report = $this->reportModel->readOne($report_index, 'index');
            $authorized = true;
        } else if($currentUserRole === 'engineer') {
            $report = $this->reportModel->readOneEngineer($report_index, 'index');
             $authorized = true;
        }
        

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

        // For multipart/form-data, data is in $_POST
        

        // Verify report existence and engineer authorization
        
        if (!$report) {
            sendJsonResponse(['message' => 'Report not found.'], 404);
            return;
        }
        
        
        // Set model properties
        $this->effectiveActionModel->report_index = $report_index;
        $this->effectiveActionModel->effective_action_title = $effective_action_title;
        $this->effectiveActionModel->created_user = $currentUserId;

        if ($this->effectiveActionModel->create()) {
            sendJsonResponse(['success' => true, 'message' => 'Effective action created successfully.', 'id' => $this->effectiveActionModel->id], 201);
        } else {
            sendJsonResponse(['message' => 'Failed to create effective action.'], 500);
        }
    }

    /**
     * Reads effective action entries for a given report index.
     *
     * @param string $reportIndex The report index to retrieve effective actions for.
     * @return void
     */
    public function readAllByReportIndex($reportIndex) {
        $currentUserRole = getCurrentUserRole();
        if (!$currentUserRole) {
            sendJsonResponse(['message' => 'Authentication required.'], 401);
            return;
        }
        $authorized = false;
        if (in_array($currentUserRole, ['superadmin', 'admin'])) {
            $report = $this->reportModel->readOne($reportIndex, 'index');
            $authorized = true;
        } else if($currentUserRole === 'engineer') {
            $report = $this->reportModel->readOneEngineer($reportIndex, 'index');
             $authorized = true;
        }
        // Verify user authorization to view this report first
        
        

        $effectiveActions = $this->effectiveActionModel->readByReportIndex($reportIndex);

        if ($effectiveActions !== false) {
            sendJsonResponse(['success' => true, 'data' => $effectiveActions], 200);
        } else {
            sendJsonResponse(['message' => 'Failed to retrieve effective actions.'], 500);
        }
    }

    /**
     * Reads a single effective action record by ID.
     *
     * @param int $id The ID of the effective action to read.
     */
    public function read($id) {
        $currentUserRole = getCurrentUserRole();
        if (!$currentUserRole) {
            sendJsonResponse(['message' => 'Authentication required.'], 401);
            return;
        }

        $this->effectiveActionModel->id = $id;
        $effectiveAction = $this->effectiveActionModel->readOne();

        if (!$effectiveAction) {
            sendJsonResponse(['message' => 'Effective action not found or unauthorized to view.'], 404);
            return;
        }

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

        sendJsonResponse($effectiveAction, 200);
    }

    /**
     * Updates an existing effective action.
     *
     * @param int $id The ID of the effective action to update.
     */
    public function update($id) {
        $currentUserRole = getCurrentUserRole();
        $currentUserId = getCurrentUserId();

        

        // For multipart/form-data (even for PUT-like behavior via POST), data is in $_POST
        $effective_action_title = $_POST['effective_action_title'] ?? null;

        if (empty($effective_action_title)) {
            sendJsonResponse(['message' => 'Missing required field: effective_action_title.'], 400);
            return;
        }

        // Fetch the effective action to get its report_index
        $this->effectiveActionModel->id = $id;
        $effectiveAction = $this->effectiveActionModel->readOne();
        if (!$effectiveAction) {
            sendJsonResponse(['message' => 'Effective action not found.'], 404);
            return;
        }

        // Verify engineer authorization for the associated report
        $report = $this->reportModel->readOne($effectiveAction['report_index'], 'index');
        $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);
        }
        
        
        

        // Set model properties for update
        $this->effectiveActionModel->effective_action_title = $effective_action_title;
        $this->effectiveActionModel->id = $id;

        if ($this->effectiveActionModel->update()) {
            sendJsonResponse(['success' => true, 'message' => 'Effective action updated successfully.'], 200);
        } else {
            sendJsonResponse(['message' => 'Failed to update effective action.'], 500);
        }
    }

    /**
     * Deletes an effective action.
     *
     * @param int $id The ID of the effective action to delete.
     */
    public function delete($id) {
        $currentUserRole = getCurrentUserRole();
        $currentUserId = getCurrentUserId();

        // Fetch the effective action to get its report_index
        $this->effectiveActionModel->id = $id;
        $effectiveAction = $this->effectiveActionModel->readOne();
        if (!$effectiveAction) {
            sendJsonResponse(['message' => 'Effective action not found.'], 404);
            return;
        }

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

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

        if ($this->effectiveActionModel->delete()) {
            sendJsonResponse(['success' => true, 'message' => 'Effective action deleted successfully.'], 200);
        } else {
            sendJsonResponse(['message' => 'Failed to delete effective action.'], 500);
        }
    }
}
?>
