<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Outputs extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');
        // // avoiding preflight requests
        $method = $_SERVER['REQUEST_METHOD'];
        if ($method == "OPTIONS") {
            die();
        }

        $this->load->helper('form');
        $this->load->library('upload');
    }
    
    
//     public function add_output()
// {
//     // Get form data
//     $activity_id = $this->input->post('activity_id');
//     $title = $this->input->post('title');
//     $status = $this->input->post('status') ?? 'Not Started';
//     $planned = $this->input->post('planned') ?? 0;
//     $achieved = $this->input->post('achieved') ?? 0;
//     $comments = $this->input->post('comments');
//     $user_id = $this->input->post('user_id');

//     // Validate required fields
//     if (empty($activity_id) || empty($title) || empty($user_id)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_INPUT'
//             )));
//     }

//     // Validate status
//     if (!in_array($status, ['Not Started', 'In Progress', 'Finalised'])) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_STATUS'
//             )));
//     }

//     // Validate activity_id exists and is active
//     $this->db->where('id', $activity_id);
//     $this->db->where('is_active', 1);
//     $activity_exists = $this->db->get('activities')->num_rows() > 0;

//     if (!$activity_exists) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_ACTIVITY_ID'
//             )));
//     }

//     // Validate user_id exists
//     $this->db->where('id', $user_id);
//     $user_exists = $this->db->get('users')->num_rows() > 0;

//     if (!$user_exists) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_USER_ID'
//             )));
//     }

//     // Prepare data for insertion
//     $data = [
//         'activity_id' => $activity_id,
//         'title' => $title,
//         'status' => $status,
//         'planned' => (int)$planned,
//         'achieved' => (int)$achieved,
//         'comments' => $comments,
//         'created_by' => $user_id,
//         'updated_by' => $user_id
//     ];

//     // Start a transaction
//     $this->db->trans_start();

//     // Insert the output
//     $insert = $this->db->insert('outputs', $data);
//     if (!$insert) {
//         $this->db->trans_rollback();
//         log_message('error', "Failed to insert output: " . $this->db->error()['message']);
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'OUTPUT_NOT_ADDED - ' . $this->db->error()['message']
//             )));
//     }

//     $output_id = $this->db->insert_id();

//     // Commit the transaction
//     $this->db->trans_complete();

//     if ($this->db->trans_status() === FALSE) {
//         log_message('error', "Transaction failed: " . $this->db->error()['message']);
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'TRANSACTION_FAILED - ' . $this->db->error()['message']
//             )));
//     }

//     $response_data = [
//         'success' => true,
//         'message' => 'OUTPUT_ADDED_SUCCESSFULLY',
//         'data' => [
//             'id' => $output_id,
//             'activity_id' => $activity_id,
//             'title' => $title,
//             'status' => $status,
//             'planned' => (int)$planned,
//             'achieved' => (int)$achieved,
//             'comments' => $comments
//         ]
//     ];

//     return $this->output
//         ->set_content_type('application/json')
//         ->set_status_header(201) // Created
//         ->set_output(json_encode($response_data));
// }

public function add_output()
{
    // Get form data
    $activity_id = $this->input->post('activity_id');
    $title = $this->input->post('title');
    $status = $this->input->post('status') ?? 'Not Started';
    $planned = $this->input->post('planned') ?? 0;
    $achieved = $this->input->post('achieved') ?? 0;
    $comments = $this->input->post('comments');
    $user_id = $this->input->post('user_id');

    // If incoming status is 'Not Started' and achieved > 0, force to 'In Progress'
    if ($status === 'Not Started' && (int)$achieved > 0) {
        $status = 'In Progress';
    }

    // Validate required fields
    if (empty($activity_id) || empty($title) || empty($user_id)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'INVALID_INPUT'
            ]));
    }

    // Validate status
    if (!in_array($status, ['Not Started', 'In Progress', 'Finalised'])) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'INVALID_STATUS'
            ]));
    }

    // Validate activity_id exists and is active
    $this->db->where('id', $activity_id);
    $this->db->where('is_active', 1);
    $activity_exists = $this->db->get('activities')->num_rows() > 0;

    if (!$activity_exists) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'INVALID_ACTIVITY_ID'
            ]));
    }

    // Validate user_id exists
    $this->db->where('id', $user_id);
    $user_exists = $this->db->get('users')->num_rows() > 0;

    if (!$user_exists) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'INVALID_USER_ID'
            ]));
    }

    // Prepare data for insertion
    $data = [
        'activity_id' => $activity_id,
        'title' => $title,
        'status' => $status,
        'planned' => (int)$planned,
        'achieved' => (int)$achieved,
        'comments' => $comments,
        'created_by' => $user_id,
        'updated_by' => $user_id
    ];

    // Start a transaction
    $this->db->trans_start();

    // Insert the output
    $insert = $this->db->insert('outputs', $data);
    if (!$insert) {
        $this->db->trans_rollback();
        log_message('error', "Failed to insert output: " . $this->db->error()['message']);
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'OUTPUT_NOT_ADDED - ' . $this->db->error()['message']
            ]));
    }

    $output_id = $this->db->insert_id();

    // Commit the transaction
    $this->db->trans_complete();

    if ($this->db->trans_status() === FALSE) {
        log_message('error', "Transaction failed: " . $this->db->error()['message']);
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'TRANSACTION_FAILED - ' . $this->db->error()['message']
            ]));
    }

    $response_data = [
        'success' => true,
        'message' => 'OUTPUT_ADDED_SUCCESSFULLY',
        'data' => [
            'id' => $output_id,
            'activity_id' => $activity_id,
            'title' => $title,
            'status' => $status,
            'planned' => (int)$planned,
            'achieved' => (int)$achieved,
            'comments' => $comments
        ]
    ];

    return $this->output
        ->set_content_type('application/json')
        ->set_status_header(201)
        ->set_output(json_encode($response_data));
}

public function edit_output($id)
{
    // Get form data
    $activity_id = $this->input->post('activity_id');
    $title = $this->input->post('title');
    $status = $this->input->post('status');
    $planned = $this->input->post('planned');
    $achieved = $this->input->post('achieved');
    $comments = $this->input->post('comments');
    $user_id = $this->input->post('user_id');

    // Validate required fields
    if (empty($user_id)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'INVALID_INPUT']));
    }

    // Validate output exists and is active
    $this->db->where('id', $id);
    $this->db->where('is_active', 1);
    $output = $this->db->get('outputs')->row_array();

    if (empty($output)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'OUTPUT_NOT_FOUND_OR_ALREADY_DELETED']));
    }

    // Determine the achieved value to use (new input or existing)
    $final_achieved = ($achieved !== null) ? (int)$achieved : (int)$output['achieved'];

    // If incoming status is 'Not Started' and achieved > 0, force to 'In Progress'
    $final_status = $status ?? $output['status']; // Use provided status or existing if not provided
    if ($final_status === 'Not Started' && $final_achieved > 0) {
        $final_status = 'In Progress';
    }

    // Validate final_status
    if (!in_array($final_status, ['Not Started', 'In Progress', 'Finalised'])) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'INVALID_STATUS']));
    }

    // Prepare data for update (only include provided fields except status, which is always updated)
    $data = [];
    if ($activity_id) $data['activity_id'] = $activity_id;
    if ($title) $data['title'] = $title;
    $data['status'] = $final_status; // Always set status based on final_status
    if ($planned !== null) $data['planned'] = (int)$planned;
    if ($achieved !== null) $data['achieved'] = (int)$achieved;
    if ($comments !== null) $data['comments'] = $comments;

    // Add audit fields
    $data['updated_by'] = $user_id;
    $data['updated_at'] = date('Y-m-d H:i:s');

    // Validate activity_id if provided
    if (isset($data['activity_id'])) {
        $this->db->where('id', $data['activity_id']);
        $this->db->where('is_active', 1);
        $activity_exists = $this->db->get('activities')->num_rows() > 0;

        if (!$activity_exists) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(400)
                ->set_output(json_encode(['success' => false, 'message' => 'INVALID_ACTIVITY_ID']));
        }
    }

    // Validate user_id exists
    $this->db->where('id', $user_id);
    $user_exists = $this->db->get('users')->num_rows() > 0;

    if (!$user_exists) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_ID']));
    }

    // Start a transaction
    $this->db->trans_start();

    // Update the output
    $this->db->where('id', $id);
    $update = $this->db->update('outputs', $data);

    if (!$update) {
        $this->db->trans_rollback();
        log_message('error', "Failed to update output: " . $this->db->error()['message']);
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'OUTPUT_NOT_UPDATED - ' . $this->db->error()['message']]));
    }

    // Commit the transaction
    $this->db->trans_complete();

    if ($this->db->trans_status() === FALSE) {
        log_message('error', "Transaction failed: " . $this->db->error()['message']);
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'TRANSACTION_FAILED - ' . $this->db->error()['message']]));
    }

    // Fetch updated output for response
    $this->db->where('id', $id);
    $updated_output = $this->db->get('outputs')->row_array();

    $response_data = [
        'success' => true,
        'message' => 'OUTPUT_UPDATED_SUCCESSFULLY',
        'data' => [
            'id' => $updated_output['id'],
            'activity_id' => $updated_output['activity_id'],
            'title' => $updated_output['title'],
            'status' => $updated_output['status'],
            'planned' => (int)$updated_output['planned'],
            'achieved' => (int)$updated_output['achieved'],
            'comments' => $updated_output['comments']
        ]
    ];

    return $this->output
        ->set_content_type('application/json')
        ->set_status_header(200)
        ->set_output(json_encode($response_data));
}

public function delete_output()
{
    // Validate user_id (assuming it's passed via GET or form for authentication)
    $id = $this->input->get("output_id");
    $user_id = $this->input->get('user_id');
    if (empty($user_id)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_USER_ID'
            )));
    }

    // Validate user exists
    $this->db->where('id', $user_id);
    $user_exists = $this->db->get('users')->num_rows() > 0;

    if (!$user_exists) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_USER_ID'
            )));
    }

    // Validate output exists and is active
    $this->db->where('id', $id);
    $this->db->where('is_active', 1);
    $output = $this->db->get('outputs')->row_array();

    if (empty($output)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'OUTPUT_NOT_FOUND_OR_ALREADY_DELETED'
            )));
    }

    // Start a transaction
    $this->db->trans_start();

    // Determine delete type (soft by default, hard if specified)
    $delete_type = $this->input->get('delete_type') ?? 'soft';
    if (!in_array($delete_type, ['soft', 'hard'])) {
        $this->db->trans_rollback();
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_DELETE_TYPE'
            )));
    }

    if ($delete_type === 'soft') {
        // Perform soft delete: update is_active to 0 and set deleted_at
        $data = [
            'is_active' => 0,
            'deleted_at' => date('Y-m-d H:i:s'), // Current timestamp
            'updated_by' => $user_id,
            'updated_at' => date('Y-m-d H:i:s') // Current timestamp
        ];

        $this->db->where('id', $id);
        $this->db->update('outputs', $data);
    } else {
        // Perform hard delete: delete the output
        $this->db->where('id', $id);
        $this->db->delete('outputs');
    }

    // Commit the transaction
    $this->db->trans_complete();

    if ($this->db->trans_status() === FALSE) {
        log_message('error', "Transaction failed: " . $this->db->error()['message']);
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500) // Internal Server Error
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'DELETE_FAILED'
            )));
    }

    return $this->output
        ->set_content_type('application/json')
        ->set_status_header(200)
        ->set_output(json_encode(array(
            'success' => true,
            'message' => ($delete_type === 'soft' ? 'OUTPUT_SOFT_DELETED_SUCCESSFULLY' : 'OUTPUT_HARD_DELETED_SUCCESSFULLY'),
            'data' => [
                'output_id' => $id,
                'delete_type' => $delete_type
            ]
        )));
}


}