<?php
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../models/User.php';
require_once '../middleware/auth.php';

$database = new Database();
$db = $database->getConnection();
$user = new User($db);

$method = $_SERVER['REQUEST_METHOD'];

switch($method) {
    case 'GET':
        // Get user profile
        $userData = authenticate();
        
        try {
            $profile = $user->getUserById($userData['user_id']);
            
            if ($profile) {
                http_response_code(200);
                echo json_encode([
                    'success' => true,
                    'user' => $profile
                ]);
            } else {
                http_response_code(404);
                echo json_encode([
                    'success' => false,
                    'message' => 'User not found'
                ]);
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode([
                'success' => false,
                'message' => 'Internal server error'
            ]);
        }
        break;

    case 'PUT':
        // Update user profile
        $userData = authenticate();
        $data = json_decode(file_get_contents("php://input"));

        if (!$data) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'Invalid JSON data'
            ]);
            break;
        }

        $user->id = $userData['user_id'];
        $user->name = isset($data->name) ? $data->name : '';
        $user->phone = isset($data->phone) ? $data->phone : '';

        try {
            if ($user->updateProfile()) {
                http_response_code(200);
                echo json_encode([
                    'success' => true,
                    'message' => 'Profile updated successfully'
                ]);
            } else {
                http_response_code(400);
                echo json_encode([
                    'success' => false,
                    'message' => 'Failed to update profile'
                ]);
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode([
                'success' => false,
                'message' => 'Internal server error'
            ]);
        }
        break;

    default:
        http_response_code(405);
        echo json_encode([
            'success' => false,
            'message' => 'Method not allowed'
        ]);
        break;
}
?>