<?php
namespace App\Controllers;

use App\Models\User;
use App\Models\Settings;
use App\Models\Order;

class AuthController extends Controller {

    public function login() {
        if ($this->session->get('customer_user')) {
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/');
        }

        $this->response->render('client/login', [
            'title' => 'Giriş Yap / Kaydol - ' . Settings::get('store_title', 'Everest Büro')
        ]);
    }

    public function logout() {
        $this->session->remove('customer_user');
        $this->session->remove('admin_user');
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/');
    }

    public function profile() {
        $customer = $this->session->get('customer_user');
        if (!$customer) {
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/login');
            return;
        }

        $user = User::find($customer['id']);
        if (!$user) {
            $this->session->remove('customer_user');
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/login');
            return;
        }

        $this->response->render('client/profile', [
            'user' => $user,
            'title' => 'Profilim - ' . Settings::get('store_title', 'Everest Büro')
        ]);
    }

    public function profileUpdate() {
        $customer = $this->session->get('customer_user');
        if (!$customer) {
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/login');
            return;
        }

        $user = User::find($customer['id']);
        if ($user) {
            $body = $this->request->getBody();
            // Google ile giriş yapanların e-posta adresi değiştirilemez (Email is readonly in view)
            $user->name = isset($body['name']) ? $body['name'] : $user->name;
            $user->phone = isset($body['phone']) ? $body['phone'] : $user->phone;
            $user->address = isset($body['address']) ? $body['address'] : $user->address;
            
            $user->save();

            // Update session with new name if changed
            $customer['name'] = $user->name;
            $this->session->set('customer_user', $customer);
            
            // Set success flash message (if we had a flash system, for now we just redirect)
        }

        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/profile?success=1');
    }

    public function orders() {
        $customer = $this->session->get('customer_user');
        if (!$customer) {
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/login');
            return;
        }

        $user = User::find($customer['id']);
        if (!$user) {
            $this->session->remove('customer_user');
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/login');
            return;
        }

        $allOrders = Order::all();
        $myOrders = [];
        foreach ($allOrders as $o) {
            if ($o->customer_email === $user->email) {
                $myOrders[] = $o;
            }
        }

        // Sort descending
        usort($myOrders, function($a, $b) {
            return strtotime($b->created_at) - strtotime($a->created_at);
        });

        $this->response->render('client/orders', [
            'user' => $user,
            'orders' => $myOrders,
            'title' => 'Siparişlerim - ' . Settings::get('store_title', 'Everest Büro')
        ]);
    }

    public function orderDetail($id) {
        $customer = $this->session->get('customer_user');
        if (!$customer) {
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/login');
            return;
        }

        $user = User::find($customer['id']);
        if (!$user) {
            $this->session->remove('customer_user');
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/login');
            return;
        }

        $order = Order::find($id);
        if (!$order || $order->customer_email !== $user->email) {
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/profile/orders');
            return;
        }

        $this->response->render('client/order_detail', [
            'user' => $user,
            'order' => $order,
            'title' => 'Sipariş Detayı #' . str_pad($order->id, 5, '0', STR_PAD_LEFT) . ' - ' . Settings::get('store_title', 'Everest Büro')
        ]);
    }

    public function uploadReceipt($id) {
        $customer = $this->session->get('customer_user');
        if (!$customer) {
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/login');
            return;
        }

        $user = User::find($customer['id']);
        if (!$user) {
            $this->session->remove('customer_user');
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/login');
            return;
        }

        $order = Order::find($id);
        if (!$order || $order->customer_email !== $user->email) {
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/profile/orders');
            return;
        }

        if (isset($_FILES['receipt']) && $_FILES['receipt']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = __DIR__ . '/../../public/uploads/receipts/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            $ext = pathinfo($_FILES['receipt']['name'], PATHINFO_EXTENSION);
            $filename = 'receipt_' . $order->id . '_' . time() . '.' . $ext;
            if (move_uploaded_file($_FILES['receipt']['tmp_name'], $uploadDir . $filename)) {
                $order->receipt_file = $filename;
                $order->status = 'payment_uploaded';
                $order->save();
            }
        }
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/profile/orders/' . $id);
    }

    public function googleRedirect() {
        if (isset($_GET['return_url']) && !empty($_GET['return_url'])) {
            $this->session->set('auth_return_url', $_GET['return_url']);
        }
        
        $clientId = Settings::get('google_client_id');
        
        if (empty($clientId)) {
            die('Google Client ID yapılandırılmamış. Lütfen yönetici paneli ayarlarından Google OAuth bilgilerini girin.');
        }

        $redirectUri = $GLOBALS['router']->getBaseUrl() . '/auth/google/callback';
        $scope = urlencode('email profile');
        $state = isset($_GET['from']) && $_GET['from'] === 'admin' ? 'admin' : 'customer';

        $authUrl = "https://accounts.google.com/o/oauth2/v2/auth?client_id={$clientId}&redirect_uri={$redirectUri}&response_type=code&scope={$scope}&state={$state}&access_type=online&prompt=select_account";
        
        $this->response->redirect($authUrl);
    }

    public function googleCallback() {
        $clientId = Settings::get('google_client_id');
        $clientSecret = Settings::get('google_client_secret');
        $redirectUri = $GLOBALS['router']->getBaseUrl() . '/auth/google/callback';

        if (empty($_GET['code'])) {
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/login?error=no_code');
        }

        $code = $_GET['code'];

        // 1. Get Access Token
        $tokenUrl = 'https://oauth2.googleapis.com/token';
        $postData = [
            'client_id' => $clientId,
            'client_secret' => $clientSecret,
            'redirect_uri' => $redirectUri,
            'grant_type' => 'authorization_code',
            'code' => $code
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $tokenUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $tokenResponse = curl_exec($ch);
        curl_close($ch);

        $tokenData = json_decode($tokenResponse, true);

        if (!isset($tokenData['access_token'])) {
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/login?error=invalid_token');
        }

        $accessToken = $tokenData['access_token'];

        // 2. Get User Profile Data
        $userUrl = 'https://www.googleapis.com/oauth2/v2/userinfo';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $userUrl);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer {$accessToken}"]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $userResponse = curl_exec($ch);
        curl_close($ch);

        $googleUser = json_decode($userResponse, true);

        if (!isset($googleUser['email'])) {
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/login?error=no_email');
        }

        $email = $googleUser['email'];
        $googleId = $googleUser['id'];
        $name = isset($googleUser['name']) ? $googleUser['name'] : explode('@', $email)[0];
        $picture = isset($googleUser['picture']) ? $googleUser['picture'] : '';

        // 3. Check if user exists in Database
        $user = User::findBy(['email' => $email]);

        if (!$user) {
            // Create new customer user
            $user = new User([
                'email' => $email,
                'name' => $name,
                'google_id' => $googleId,
                'avatar' => $picture,
                'role' => 'customer',
                'created_at' => date('Y-m-d H:i:s')
            ]);
            $user->save();
        } else {
            // Update existing user with google_id and avatar if missing
            $updated = false;
            if (!$user->google_id) {
                $user->google_id = $googleId;
                $updated = true;
            }
            if (!$user->avatar && $picture) {
                $user->avatar = $picture;
                $updated = true;
            }
            if ($updated) {
                $user->save();
            }
        }

        // 4. Log the user in via Session
        $this->session->set('customer_user', [
            'id' => $user->id,
            'email' => $user->email,
            'name' => $user->name,
            'avatar' => $user->avatar,
            'role' => $user->role
        ]);

        if ($user->role === 'admin') {
            $this->session->set('admin_user', [
                'id' => $user->id,
                'email' => $user->email,
                'name' => $user->name,
                'role' => $user->role,
                'avatar' => $user->avatar
            ]);
        }

        $authReturnUrl = $this->session->get('auth_return_url');
        if ($authReturnUrl) {
            $this->session->remove('auth_return_url');
            $this->response->redirect($authReturnUrl);
            return;
        }

        $returnUrl = $this->session->get('admin_return_url');
        if ($user->role === 'admin' && $returnUrl) {
            $this->session->remove('admin_return_url');
            $this->response->redirect($returnUrl);
            return;
        }

        // Google'dan dönen state parametresine göre yönlendir
        $state = isset($_GET['state']) ? $_GET['state'] : 'customer';
        if ($state === 'admin') {
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin');
        } else {
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/');
        }
    }
}
