<?php
include_once __DIR__ . '/../config/database.php';

class PaymentController {
    private $db;

    public function __construct() {
        $database = new Database();
        $this->db = $database->getConnection();
    }

    private function verifyAuth() {
        $headers = apache_request_headers();
        $token = isset($headers['Authorization']) ? str_replace('Bearer ', '', $headers['Authorization']) : null;
        if (!$token) return null;
        $decoded = json_decode(base64_decode($token), true);
        return ($decoded && isset($decoded['id'])) ? $decoded : null;
    }

    public function pay($data) {
        $user = $this->verifyAuth();
        if (!$user) { http_response_code(401); echo json_encode(["message" => "Unauthorized"]); return; }

        if (empty($data->amount) || $data->amount <= 0) {
            http_response_code(400); echo json_encode(["message" => "Некорректная сумма"]); return;
        }
        if (empty($data->provider)) {
            http_response_code(400); echo json_encode(["message" => "Укажите провайдера"]); return;
        }

        $userId = $user['id'];
        $amount = floatval($data->amount);

        try {
            $this->db->beginTransaction();
            $stmt = $this->db->prepare("SELECT id, balance FROM accounts WHERE user_id = ? LIMIT 1");
            $stmt->execute([$userId]);
            $account = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$account || $account['balance'] < $amount) {
                throw new Exception("Недостаточно средств");
            }
            $stmt = $this->db->prepare("UPDATE accounts SET balance = balance - ? WHERE id = ?");
            $stmt->execute([$amount, $account['id']]);

            $stmt = $this->db->prepare("INSERT INTO payments (user_id, category, provider, account_number, amount, status) VALUES (?, ?, ?, ?, ?, 'completed')");
            $stmt->execute([$userId, $data->category ?? 'other', $data->provider, $data->account_number ?? null, $amount]);

            $trxId = 'PAY-' . rand(100000, 999999);
            $stmt = $this->db->prepare("INSERT INTO transactions (transaction_id, sender_id, amount, type, status) VALUES (?, ?, ?, 'Payment', 'Completed')");
            $stmt->execute([$trxId, $userId, $amount]);

            // Push notification
            $stmt = $this->db->prepare("INSERT INTO notifications (user_id, title, message, type) VALUES (?, ?, ?, 'warning')");
            $msg = "Списано \${$amount} — {$data->provider}";
            $stmt->execute([$userId, "Платёж выполнен", $msg]);

            $this->db->commit();
            http_response_code(200);
            echo json_encode(["message" => "Платёж выполнен успешно!"]);
        } catch (Exception $e) {
            $this->db->rollBack();
            http_response_code(400);
            echo json_encode(["message" => $e->getMessage()]);
        }
    }

    public function getPayments() {
        $user = $this->verifyAuth();
        if (!$user) { http_response_code(401); echo json_encode(["message" => "Unauthorized"]); return; }
        $stmt = $this->db->prepare("SELECT * FROM payments WHERE user_id = ? ORDER BY created_at DESC LIMIT 20");
        $stmt->execute([$user['id']]);
        echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
    }

    public function getNotifications() {
        $user = $this->verifyAuth();
        if (!$user) { http_response_code(401); echo json_encode(["message" => "Unauthorized"]); return; }
        $stmt = $this->db->prepare("SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT 30");
        $stmt->execute([$user['id']]);
        echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
    }

    public function markNotificationsRead() {
        $user = $this->verifyAuth();
        if (!$user) { http_response_code(401); echo json_encode(["message" => "Unauthorized"]); return; }
        $stmt = $this->db->prepare("UPDATE notifications SET is_read = 1 WHERE user_id = ?");
        $stmt->execute([$user['id']]);
        echo json_encode(["message" => "ok"]);
    }

    public function blockCard($data) {
        $user = $this->verifyAuth();
        if (!$user) { http_response_code(401); echo json_encode(["message" => "Unauthorized"]); return; }
        if (empty($data->card_id)) { http_response_code(400); echo json_encode(["message" => "card_id required"]); return; }
        $status = isset($data->status) ? $data->status : 'blocked';
        $stmt = $this->db->prepare("UPDATE cards SET status = ? WHERE id = ? AND user_id = ?");
        $stmt->execute([$status, $data->card_id, $user['id']]);

        $action = $status === 'active' ? 'разблокирована' : 'заблокирована';
        $notifStmt = $this->db->prepare("INSERT INTO notifications (user_id, title, message, type) VALUES (?, ?, ?, ?)");
        $notifType = $status === 'active' ? 'success' : 'warning';
        $notifStmt->execute([$user['id'], "Карта $action", "Ваша карта была $action", $notifType]);

        http_response_code(200);
        echo json_encode(["message" => "Статус карты обновлён"]);
    }

    public function updateCardLimit($data) {
        $user = $this->verifyAuth();
        if (!$user) { http_response_code(401); echo json_encode(["message" => "Unauthorized"]); return; }
        if (empty($data->card_id)) { http_response_code(400); echo json_encode(["message" => "card_id required"]); return; }

        $fields = [];
        $params = [];
        if (isset($data->daily_limit)) { $fields[] = "daily_limit = ?"; $params[] = floatval($data->daily_limit); }
        if (isset($data->monthly_limit)) { $fields[] = "monthly_limit = ?"; $params[] = floatval($data->monthly_limit); }
        if (empty($fields)) { http_response_code(400); echo json_encode(["message" => "Nothing to update"]); return; }

        $params[] = $data->card_id;
        $params[] = $user['id'];
        $stmt = $this->db->prepare("UPDATE cards SET " . implode(', ', $fields) . " WHERE id = ? AND user_id = ?");
        $stmt->execute($params);

        http_response_code(200);
        echo json_encode(["message" => "Лимиты обновлены"]);
    }
}
?>
