<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Activities 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_activity()
{
    // Get JSON data from the request body
    $json_data = json_decode(file_get_contents('php://input'), true);

    if (empty($json_data) || !isset($json_data['outcome_id']) || !isset($json_data['code']) || !isset($json_data['name']) || !isset($json_data['team_id']) || !isset($json_data['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'
            )));
    }

    // Prepare data for insertion
    $data = array(
        'outcome_id' => $json_data['outcome_id'],
        'code' => $json_data['code'],
        'name' => $json_data['name'],
        'progress' => isset($json_data['progress']) ? $json_data['progress'] : 0,
        'status' => isset($json_data['status']) ? $json_data['status'] : 'Not Started',
        'created_at' => isset($json_data['created_at']) ? date('Y-m-d', strtotime($json_data['created_at'])) : date('Y-m-d'),
        'location' => isset($json_data['location']) ? $json_data['location'] : 'TBD',
        'has_sub_activities' => isset($json_data['has_sub_activities']) ? $json_data['has_sub_activities'] : 0,
        'has_follow_up_activities' => isset($json_data['has_follow_up_activities']) ? $json_data['has_follow_up_activities'] : 0,
        'team_id' => $json_data['team_id'],
        'comments_count' => isset($json_data['comments_count']) ? $json_data['comments_count'] : 0,
        'created_by' => $json_data['user_id'],
        'updated_by' => $json_data['user_id']
    );

    // Validate status (must be 'Not Started', 'In Progress', or 'Finalised')
    if (!in_array($data['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 has_sub_activities and has_follow_up_activities (must be 0 or 1)
    if (!in_array($json_data['has_sub_activities'], [0, 1]) || !in_array($json_data['has_follow_up_activities'], [0, 1])) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_ACTIVITY_FLAGS'
            )));
    }

    // Validate outcome_id exists in outcomes table
    $this->db->where('id', $json_data['outcome_id']);
    $outcome_exists = $this->db->get('outcomes')->num_rows() > 0;

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

    // Validate team_id exists in teams table
    $this->db->where('id', $json_data['team_id']);
    $team_exists = $this->db->get('teams')->num_rows() > 0;

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

    // Validate user_id exists in users table
    $this->db->where('id', $json_data['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'
            )));
    }

    // Insert the activity into the database
    $insert = $this->db->insert('activities', $data);

    if ($insert) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(201) // Created
            ->set_output(json_encode(array(
                'success' => true,
                'message' => 'ACTIVITY_ADDED_SUCCESSFULLY',
                'data' => array('id' => $this->db->insert_id()) // Return the new ID
            )));
    } else {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'ACTIVITY_NOT_ADDED'
            )));
    }
}


public function edit_activity($id)
{
    // Get form data from JSON input
    $json_data = json_decode(@file_get_contents('php://input'), true);
    $outcome_id = $json_data['outcome_id'];
    $name = $json_data['name'];
    $code = $json_data['code'];
    $progress = $json_data['progress'];
    $status = $json_data['status'];
    $location = $json_data['location'];
    $has_sub_activities = $json_data['has_sub_activities'];
    $has_follow_up_activities = $json_data['has_follow_up_activities'];
    $team_id = $json_data['team_id'];
    $user_id = $json_data['user_id'];
    $months = $json_data['months'] ?? []; // Array of month names or comma-separated string

    // Validate required fields
    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_INPUT'
            )));
    }

    // 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 activity exists and is active
    $this->db->where('id', $id);
    $this->db->where('is_active', 1); // Ensure the activity is active
    $activity = $this->db->get('activities')->row_array();

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

    // Validate outcome if provided
    if ($outcome_id) {
        $this->db->where('id', $outcome_id);
        $this->db->where('is_active', 1); // Assuming soft delete with is_active
        $outcome = $this->db->get('outcomes')->row_array();

        if (empty($outcome)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(400) // Bad Request
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'INVALID_OUTCOME'
                )));
        }
    } else {
        $outcome_id = $activity['outcome_id']; // Default to existing outcome_id
        $this->db->where('id', $outcome_id);
        $this->db->where('is_active', 1); // Assuming soft delete with is_active
        $outcome = $this->db->get('outcomes')->row_array();
    }

    // Validate status if provided
    if ($status && !in_array($status, ['Not Started', 'In Progress', 'Completed'])) {
        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 code (numeric, optional, defaults to existing value if not provided)
    $code = $code !== null ? floatval($code) : $activity['code'];

    // Validate progress (numeric string, defaults to existing value if not provided)
    $progress = $progress !== null && is_numeric($progress) ? (string)$progress : $activity['progress'];

    // Validate has_sub_activities and has_follow_up_activities (boolean/integer, defaults to existing values)
    $has_sub_activities = $has_sub_activities !== null ? (int)$has_sub_activities : $activity['has_sub_activities'];
    $has_follow_up_activities = $has_follow_up_activities !== null ? (int)$has_follow_up_activities : $activity['has_follow_up_activities'];

    // Validate team_id if provided
    if ($team_id) {
        $this->db->where('id', $team_id);
        $this->db->where('is_active', 1); // Assuming soft delete with is_active
        $team_exists = $this->db->get('teams')->num_rows() > 0;

        if (!$team_exists) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(400) // Bad Request
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'INVALID_TEAM_ID'
                )));
        }
    } else {
        $team_id = $activity['team_id']; // Default to existing team_id
    }

    // Validate months (array of valid month names, defaults to existing months if not provided)
    $valid_months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    if (!empty($months) && !is_array($months)) {
        $months = explode(',', $months); // Handle comma-separated string if passed
    }
    $months = array_filter(array_map('trim', (array)$months), function($month) use ($valid_months) {
        return in_array($month, $valid_months);
    });
    if (empty($months)) {
        // Get existing active months for the activity
        $this->db->select('month');
        $this->db->where('activity_id', $id);
        $this->db->where('is_active', 1); // Ensure active months only
        $existing_months = $this->db->get('activity_months')->result_array();
        $months = array_column($existing_months, 'month');
    }

    // Prepare data for update (only include provided fields)
    $data = array();
    if ($name) $data['name'] = $name;
    if ($code !== null) $data['code'] = $code;
    if ($progress !== null) $data['progress'] = $progress;
    if ($status) $data['status'] = $status;
    if ($location) $data['location'] = $location;
    if ($has_sub_activities !== null) $data['has_sub_activities'] = (int)$has_sub_activities;
    if ($has_follow_up_activities !== null) $data['has_follow_up_activities'] = (int)$has_follow_up_activities;
    if ($team_id) $data['team_id'] = $team_id;
    if ($outcome_id) $data['outcome_id'] = $outcome_id;

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

    // Start a transaction to ensure data consistency
    $this->db->trans_start();

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

    if (!$update) {
        $this->db->trans_rollback();
        log_message('error', "Failed to update activity: " . $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' => 'ACTIVITY_NOT_UPDATED - ' . $this->db->error()['message']
            )));
    }

    // Handle activity months
    if (!empty($months)) {
        // Get existing active months for this activity
        $this->db->select('month');
        $this->db->where('activity_id', $id);
        $this->db->where('is_active', 1);
        $existing_active_months = $this->db->get('activity_months')->result_array();
        $existing_active_months = array_column($existing_active_months, 'month');

        // Identify months to insert (those not already active)
        $new_months = array_diff($months, $existing_active_months);

        if (!empty($new_months)) {
            $month_data = array_map(function($month) use ($id, $user_id) {
                return [
                    'activity_id' => $id,
                    'month' => $month,
                    'created_by' => $user_id,
                    'updated_by' => $user_id
                ];
            }, $new_months);

            $this->db->insert_batch('activity_months', $month_data);
            if ($this->db->affected_rows() === FALSE) {
                $this->db->trans_rollback();
                log_message('error', "Failed to insert activity months: " . $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' => 'ACTIVITY_MONTHS_NOT_UPDATED - ' . $this->db->error()['message']
                    )));
            }
        }

        // Soft-delete any active months not in the new list
        $months_to_delete = array_diff($existing_active_months, $months);
        if (!empty($months_to_delete)) {
            $this->db->where('activity_id', $id);
            $this->db->where_in('month', $months_to_delete);
            $this->db->set('is_active', 0);
            $this->db->set('deleted_at', date('Y-m-d H:i:s'));
            $this->db->set('updated_by', $user_id);
            $this->db->set('updated_at', date('Y-m-d H:i:s'));
            $this->db->update('activity_months');
        }

        // Restore soft-deleted months if they’re in the new list
        $soft_deleted_months = array_intersect($months, array_column($this->db->where('activity_id', $id)->where('is_active', 0)->get('activity_months')->result_array(), 'month'));
        if (!empty($soft_deleted_months)) {
            $this->db->where('activity_id', $id);
            $this->db->where_in('month', $soft_deleted_months);
            $this->db->set('is_active', 1);
            $this->db->set('deleted_at', NULL);
            $this->db->set('updated_by', $user_id);
            $this->db->set('updated_at', date('Y-m-d H:i:s'));
            $this->db->update('activity_months');
        }
    } else {
        // If no months provided, soft-delete all existing active months
        $this->db->where('activity_id', $id);
        $this->db->where('is_active', 1);
        $this->db->set('is_active', 0);
        $this->db->set('deleted_at', date('Y-m-d H:i:s'));
        $this->db->set('updated_by', $user_id);
        $this->db->set('updated_at', date('Y-m-d H:i:s'));
        $this->db->update('activity_months');
    }

    // 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']
            )));
    }

    // Fetch updated activity and related data for response
    $this->db->where('id', $id);
    $updated_activity = $this->db->get('activities')->row_array();

    $this->db->select('o.title');
    $this->db->where('o.id', $updated_activity['outcome_id']);
    $outcome = $this->db->get('outcomes o')->row_array();

    // Get current active months for the response
    $this->db->select('month');
    $this->db->where('activity_id', $id);
    $this->db->where('is_active', 1);
    $current_months = $this->db->get('activity_months')->result_array();
    $months = array_column($current_months, 'month');

    $response_data = [
        'id' => (string)$updated_activity['id'], // Convert to string to match your response
        'progress' => (string)$updated_activity['progress'],
        'name' => $updated_activity['name'],
        'code' => floatval($updated_activity['code']), // Convert decimal to float
        'months' => $months, 
        'team' => $this->get_team_details($updated_activity['team_id']), // Fetch team details
        'status' => $updated_activity['status'],
        'outcome' => $outcome['title'], // Use outcome title
        'created_at' => $updated_activity['created_at'],
        'location' => $updated_activity['location'],
        'followUpActivities' => [], // Placeholder
        'hasFollowUpActivities' => (bool)$updated_activity['has_follow_up_activities'],
        'hasSubActivities' => (bool)$updated_activity['has_sub_activities'],
        'subActivities' => [], // Placeholder
        'outputs' => $this->get_outputs_for_activity($id),
        'comments' => [], // Placeholder
        'comments_count' => (string)$updated_activity['comments_count'], // Convert to string to match your response
        'products' => $this->get_products_for_activity($id), // Populate products
        'outputProducts' => $this->get_output_products_for_activity($id), // Populate output products
        'attachments' => [] // Placeholder
    ];

    return $this->output
        ->set_content_type('application/json')
        ->set_status_header(200)
        ->set_output(json_encode(array(
            'success' => true,
            'message' => 'ACTIVITY_UPDATED_SUCCESSFULLY',
            'data' => $response_data
        )));
}
    // function to get activity by id

    public function get_activity($id)
    {
        
    }

    // function to edit activity
    
    

    // function to delete activity
    public function delete_activity($id)
    {
        
    }

    // function to get all activitys
    public function get_all_activities()
    {
        
    }

    // function to add product to activity
     public function add_product_to_activity($activity_id){

     }

     // function to edit product in activity
    public function edit_product_in_activity($activity_id, $product_id){
        // edits title, description, 
    }

     // function to remove product from activity
    public function remove_product_from_activity($activity_id, $product_id){
    
    }

    // function to get all products in activity

    public function get_all_products_in_activity($activity_id){
        // returns all products in activity in an array
    }


    // function to add sub activity to activity
     public function add_sub_activity_to_activity($activity_id, $user_id){

     }

     // function to get all sub activities in activity
     public function get_all_sub_activities_in_activity($activity_id){

     }

    // function to edit sub activity in activity

     public function edit_sub_activity_in_activity($activity_id, $sub_activity_id){
    }

    // function to remove sub activity from activity

    public function remove_sub_activity_from_activity($activity_id, $sub_activity_id){
    
    }

    // function to add user to activity
     public function add_user_to_activity($activity_id, $user_id){

     }

     // function to get all users in activity
     public function get_all_users_in_activity($activity_id){

     }

    // function to edit user in activity

     public function edit_user_in_activity($activity_id, $user_id){
    }

    // function to remove user from activity

    public function remove_user_from_activity($activity_id, $user_id){
    
    }

    public function get_all_activities_by_user($user_id){
        // returns all activities by user
    }

    public function send_reminder($activity_id){
        // sends reminder to all users in activity
    }

    public function get_activities_by_status($status){
        // returns all activities by status
    }



    public function set_reminder($activity_id){
        // sets reminder for activity 
        // a user sets when to be reminded eg, 1 day before, 1 week before so in the database, we set the reminder date and time
        // a cron job for reminders will be set to run every day and minute to check if there is a reminder for that day and time
    }

    public function send_reminder_to_users($activity_id){
        // sends reminder to all users in activity
    }
    


}