<?php
// controllers/PreventionController.php

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

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

    /**
     * Creates a new prevention record for a report.
     * Only engineers assigned to the report can create.
     */
    public function create() {
        $currentUserRole = getCurrentUserRole();
        $currentUserId = getCurrentUserId();
         $report_index = $_POST['report_index'] ?? null;
        $prevention_title = $_POST['prevention_title'] ?? null;

        // Validate required fields
        if (empty($report_index) || empty($prevention_title)) {
            sendJsonResponse(['message' => 'Missing required fields: report_index, prevention_title.'], 400);
            return; // Added 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; // Added return
        }
        

        // Set model properties
        $this->preventionModel->report_index = $report_index;
        $this->preventionModel->prevention_title = $prevention_title;
        $this->preventionModel->created_user = $currentUserId;

        if ($this->preventionModel->create()) {
            sendJsonResponse(['success' => true, 'message' => 'Prevention record created successfully.', 'id' => $this->preventionModel->id], 201);
        } else {
            sendJsonResponse(['message' => 'Failed to create prevention record.'], 500);
        }
    }

    /**
     * Reads prevention entries for a given report index.
     * Access is based on report view permissions.
     *
     * @param string $reportIndex The report index to retrieve prevention steps for.
     */
    public function readByReportIndex($reportIndex) {
        $currentUserRole = getCurrentUserRole();
        if (!$currentUserRole) {
            sendJsonResponse(['message' => 'Authentication required.'], 401);
            return; // Added return
        }
        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;
        }

        
       

        $preventionActions = $this->preventionModel->readByReportIndex($reportIndex);

        if ($preventionActions !== false) {
            sendJsonResponse(['success' => true, 'data' => $preventionActions], 200); // Added success and data keys
        } else {
            sendJsonResponse(['message' => 'Failed to retrieve prevention steps.'], 500);
        }
    }

    /**
     * Updates an existing prevention record.
     * Only the engineer assigned to the report can update.
     *
     * @param int $id The ID of the prevention record 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
        $prevention_title = $_POST['prevention_title'] ?? null;

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

        // Fetch the prevention record to get its report_index
        $this->preventionModel->id = $id;
        $prevention = $this->preventionModel->readOne();
        if (!$prevention) {
            sendJsonResponse(['message' => 'Prevention record not found.'], 404);
            return; // Added return
        }

        // Verify engineer authorization for the associated report
        $report = $this->reportModel->readOne($prevention['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->preventionModel->prevention_title = $prevention_title;
        $this->preventionModel->id = $id;

        if ($this->preventionModel->update()) {
            sendJsonResponse(['success' => true, 'message' => 'Prevention record updated successfully.'], 200); // Added success key
        } else {
            sendJsonResponse(['message' => 'Failed to update prevention record.'], 500);
        }
    }

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

        // Fetch the prevention record to get its report_index
        $this->preventionModel->id = $id;
        $prevention = $this->preventionModel->readOne();
        if (!$prevention) {
            sendJsonResponse(['message' => 'Prevention record not found.'], 404);
            return; // Added return
        }

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

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

        if ($this->preventionModel->delete()) {
            sendJsonResponse(['success' => true, 'message' => 'Prevention record deleted successfully.'], 200); // Added success key
        } else {
            sendJsonResponse(['message' => 'Failed to delete prevention record.'], 500);
        }
    }
}
?>
