<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../models/WorkHour.php';

class WorkHourAPI {
    private $conn;
    private $workHour;
    
    public function __construct() {
        $database = new Database();
        $this->conn = $database->getConnection();
        $this->workHour = new WorkHour($this->conn);
    }
    
    public function create($data) {
        $this->workHour->task_id = $data['task_id'];
        $this->workHour->user_id = $data['user_id'];
        $this->workHour->date = $data['date'];
        $this->workHour->hours = $data['hours'];
        $this->workHour->description = $data['description'] ?? '';
        $this->workHour->rate = $data['rate'] ?? null;
        
        // Calculate total amount if rate is provided
        if ($this->workHour->rate) {
            $this->workHour->total_amount = $this->workHour->hours * $this->workHour->rate;
        }
        
        if ($this->workHour->create()) {
            return [
                'success' => true,
                'message' => 'Work hour entry created successfully',
                'id' => $this->conn->lastInsertId()
            ];
        }
        
        return [
            'success' => false,
            'message' => 'Failed to create work hour entry'
        ];
    }
    
    public function getAll($task_id = null, $user_id = null) {
        if ($task_id) {
            $stmt = $this->workHour->readByTask($task_id);
        } elseif ($user_id) {
            // For user-specific queries, we'd need to add a readByUser method
            $stmt = $this->workHour->read();
        } else {
            $stmt = $this->workHour->read();
        }
        
        $workHours = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $workHours[] = $row;
        }
        
        return [
            'success' => true,
            'data' => $workHours
        ];
    }
    
    public function getById($id) {
        $this->workHour->id = $id;
        $this->workHour->readOne();
        
        if ($this->workHour->id) {
            return [
                'success' => true,
                'data' => [
                    'id' => $this->workHour->id,
                    'task_id' => $this->workHour->task_id,
                    'user_id' => $this->workHour->user_id,
                    'date' => $this->workHour->date,
                    'hours' => $this->workHour->hours,
                    'description' => $this->workHour->description,
                    'rate' => $this->workHour->rate,
                    'total_amount' => $this->workHour->total_amount,
                    'created_at' => $this->workHour->created_at,
                    'updated_at' => $this->workHour->updated_at
                ]
            ];
        }
        
        return [
            'success' => false,
            'message' => 'Work hour entry not found'
        ];
    }
    
    public function update($id, $data) {
        $this->workHour->id = $id;
        $this->workHour->task_id = $data['task_id'];
        $this->workHour->user_id = $data['user_id'];
        $this->workHour->date = $data['date'];
        $this->workHour->hours = $data['hours'];
        $this->workHour->description = $data['description'] ?? '';
        $this->workHour->rate = $data['rate'] ?? null;
        
        // Recalculate total amount if rate is provided
        if ($this->workHour->rate) {
            $this->workHour->total_amount = $this->workHour->hours * $this->workHour->rate;
        }
        
        if ($this->workHour->update()) {
            return [
                'success' => true,
                'message' => 'Work hour entry updated successfully'
            ];
        }
        
        return [
            'success' => false,
            'message' => 'Failed to update work hour entry'
        ];
    }
    
    public function delete($id) {
        $this->workHour->id = $id;
        
        if ($this->workHour->delete()) {
            return [
                'success' => true,
                'message' => 'Work hour entry deleted successfully'
            ];
        }
        
        return [
            'success' => false,
            'message' => 'Failed to delete work hour entry'
        ];
    }
    
    public function getTaskSummary($task_id) {
        $summary = $this->workHour->getTotalHoursByTask($task_id);
        
        return [
            'success' => true,
            'data' => $summary
        ];
    }
}

// Handle API requests
$method = $_SERVER['REQUEST_METHOD'];

try {
    $api = new WorkHourAPI();
    
    switch ($method) {
        case 'GET':
            $task_id = $_GET['task_id'] ?? null;
            $user_id = $_GET['user_id'] ?? null;
            $result = $api->getAll($task_id, $user_id);
            echo json_encode($result);
            break;
            
        case 'POST':
            $data = json_decode(file_get_contents('php://input'), true);
            $result = $api->create($data);
            echo json_encode($result);
            break;
            
        case 'PUT':
            $data = json_decode(file_get_contents('php://input'), true);
            $id = $data['id'];
            $result = $api->update($id, $data);
            echo json_encode($result);
            break;
            
        case 'DELETE':
            $id = $_GET['id'];
            $result = $api->delete($id);
            echo json_encode($result);
            break;
            
        default:
            echo json_encode([
                'success' => false,
                'message' => 'Invalid request method'
            ]);
            break;
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
