<?php

namespace App\Http\Controllers\api\v1;

use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\BaseController;

class TaskControllerREST extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $query = DB::table('tasks')
            ->select('tasks.*', 'users.first_name', 'users.last_name', 'clients.name as client_name')
            ->leftJoin('users', 'users.id', '=', 'tasks.assigned_to')
            ->leftJoin('clients', 'clients.id', '=', 'tasks.client_id')
            ->orderBy('tasks.created_at', 'desc');

        // Apply filters
        if (request()->get('assigned_to')) {
            $query->where('tasks.assigned_to', request()->get('assigned_to'));
        }

        if (request()->get('type')) {
            $query->where('tasks.type', request()->get('type'));
        }

        if (request()->get('status')) {
            $query->where('tasks.status_id', request()->get('status'));
        }

        if (request()->get('completed') && request()->get('completed') != 'false') {
            $query->where('tasks.completed', 1);
        }

        if (request()->get('open') && request()->get('open') != 'false') {
            $query->where('tasks.completed', 0);
        }

        $query = $query->paginate(request()->get('limit', 20));

        // Sanitize data to remove control characters that cause JSON encoding errors
        $data = $query->getCollection()->toArray();
        array_walk_recursive($data, function(&$item) {
            if (is_string($item)) {
                // Remove control characters except newline and tab
                $item = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $item);
            }
        });

        $response = [
            'success'      => true,
            'data'         => $data,
            'total'        => $query->total(),
            'current_page' => $query->currentPage(),
            'last_page'    => $query->lastPage(),
        ];

        return Response::json($response);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        $data = request()->all();
        
        $taskId = DB::table('tasks')->insertGetId([
            'name' => $data['name'],
            'description' => $data['description'] ?? '',
            'assigned_to' => $data['assigned_to'] ?? auth()->id(),
            'client_id' => $data['client_id'] ?? null,
            'type' => $data['type'] ?? 'task',
            'status_id' => $data['status_id'] ?? 1,
            'priority' => $data['priority'] ?? 'medium',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return Response::json(['success' => true, 'task_id' => $taskId]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        $task = DB::table('tasks')
            ->select('tasks.*', 'users.first_name', 'users.last_name', 'clients.name as client_name')
            ->leftJoin('users', 'users.id', '=', 'tasks.assigned_to')
            ->leftJoin('clients', 'clients.id', '=', 'tasks.client_id')
            ->where('tasks.id', $id)
            ->first();

        if (!$task) {
            return Response::json(['error' => 'Task not found'], 404);
        }

        // Sanitize data to remove control characters that cause JSON encoding errors
        $taskArray = (array) $task;
        array_walk_recursive($taskArray, function(&$item) {
            if (is_string($item)) {
                // Remove control characters except newline and tab
                $item = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $item);
            }
        });

        return Response::json($taskArray);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function update($id)
    {
        $task = DB::table('tasks')->where('id', $id)->first();

        if (!$task) {
            return Response::json(['error' => 'Task not found'], 404);
        }

        $data = request()->all();
        $data['updated_at'] = now();

        DB::table('tasks')->where('id', $id)->update($data);

        return Response::json(['success' => true, 'message' => 'Task updated']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        $task = DB::table('tasks')->where('id', $id)->first();

        if (!$task) {
            return Response::json(['error' => 'Task not found'], 404);
        }

        DB::table('tasks')->where('id', $id)->delete();

        return Response::json(['success' => true, 'message' => 'Task deleted']);
    }
} 