<?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';

class Task {
    private $conn;
    private $table = 'tasks';
    
    public function __construct($db) {
        $this->conn = $db;
    }
    
    public function create($data) {
        $sql = "INSERT INTO {$this->table} (title, description, status, priority, project_id, due_date, created_at, updated_at) 
                  VALUES (:title, :description, :status, :priority, :project_id, :due_date, NOW(), NOW())";
        
        $stmt = $this->conn->prepare($sql);
        $stmt->bindParam(':title', $data['title']);
        $stmt->bindParam(':description', $data['description']);
        $stmt->bindParam(':status', $data['status']);
        $stmt->bindParam(':priority', $data['priority']);
        $stmt->bindParam(':project_id', $data['project_id']);
        $stmt->bindParam(':due_date', $data['due_date']);
        
        if ($stmt->execute()) {
            return [
                'success' => true,
                'message' => 'Task created successfully',
                'id' => $this->conn->lastInsertId()
            ];
        }
        
        return [
            'success' => false,
            'message' => 'Failed to create task'
        ];
    }
    
    public function getAll($projectId = null) {
        $sql = "SELECT t.*, p.project_name 
                  FROM {$this->table} t 
                  LEFT JOIN projects p ON t.project_id = p.id 
                  WHERE 1=1";
        
        if ($projectId) {
            $sql .= " AND t.project_id = :project_id";
        }
        
        $sql .= " ORDER BY t.created_at DESC";
        
        $stmt = $this->conn->prepare($sql);
        
        if ($projectId) {
            $stmt->bindParam(':project_id', $projectId);
        }
        
        $stmt->execute();
        
        $tasks = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        return [
            'success' => true,
            'data' => $tasks
        ];
    }
    
    public function getById($id) {
        $sql = "SELECT t.*, p.project_name 
                  FROM {$this->table} t 
                  LEFT JOIN projects p ON t.project_id = p.id 
                  WHERE t.id = :id";
        
        $stmt = $this->conn->prepare($sql);
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        
        $task = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($task) {
            return [
                'success' => true,
                'data' => $task
            ];
        }
        
        return [
            'success' => false,
            'message' => 'Task not found'
        ];
    }
    
    public function update($id, $data) {
        $sql = "UPDATE {$this->table} 
                  SET title = :title, description = :description, status = :status, 
                      priority = :priority, project_id = :project_id, due_date = :due_date, updated_at = NOW() 
                  WHERE id = :id";
        
        $stmt = $this->conn->prepare($sql);
        $stmt->bindParam(':title', $data['title']);
        $stmt->bindParam(':description', $data['description']);
        $stmt->bindParam(':status', $data['status']);
        $stmt->bindParam(':priority', $data['priority']);
        $stmt->bindParam(':project_id', $data['project_id']);
        $stmt->bindParam(':due_date', $data['due_date']);
        $stmt->bindParam(':id', $id);
        
        if ($stmt->execute()) {
            return [
                'success' => true,
                'message' => 'Task updated successfully'
            ];
        }
        
        return [
            'success' => false,
            'message' => 'Failed to update task'
        ];
    }
    
    public function delete($id) {
        $sql = "DELETE FROM {$this->table} WHERE id = :id";
        
        $stmt = $this->conn->prepare($sql);
        $stmt->bindParam(':id', $id);
        
        if ($stmt->execute()) {
            return [
                'success' => true,
                'message' => 'Task deleted successfully'
            ];
        }
        
        return [
            'success' => false,
            'message' => 'Failed to delete task'
        ];
    }
}

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

try {
    $database = new Database();
    $conn = $database->getConnection();
    $task = new Task($conn);
    
    switch ($method) {
        case 'GET':
            $projectId = $_GET['project_id'] ?? null;
            $result = $task->getAll($projectId);
            echo json_encode($result);
            break;
            
        case 'POST':
            $data = json_decode(file_get_contents('php://input'), true);
            $result = $task->create($data);
            echo json_encode($result);
            break;
            
        case 'PUT':
            $data = json_decode(file_get_contents('php://input'), true);
            $id = $data['id'];
            $result = $task->update($id, $data);
            echo json_encode($result);
            break;
            
        case 'DELETE':
            $id = $_GET['id'];
            $result = $task->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()
    ]);
}
?>
