<?php
namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;
use App\Models\ContactModel; // You'll need to create this Model too

    class ContactController extends ResourceController {
        protected $format = 'json';
    
        public function addContacts() {
        $this->response->setHeader('Access-Control-Allow-Origin', '*');
        
        // Get the raw JSON body from Flutter
        $json = $this->request->getJSON(); 
        
        if (!$json || !isset($json->contacts)) {
            return $this->fail('No contacts data received');
        }
    
        $db = \Config\Database::connect();
        $builder = $db->table('emergency_contacts');
    
        foreach ($json->contacts as $contact) {
            $builder->insert([
                'user_id'       => $json->user_id,
                'contact_name'  => $contact->name,
                'contact_phone' => $contact->phone,
                'priority'      => 1
            ]);
        }
    
        return $this->respondCreated(['status' => 201, 'message' => 'Contacts synchronized']);
    }
    
    public function get_user_data()
    {
        //$phone = trim($this->request->getVar('phone'));
        $user_id = trim($this->request->getVar('user_id'));
        /*$name = trim($this->request->getVar('name'));
        $pin = trim($this->request->getVar('user_pin'));
        $panic = trim($this->request->getVar('panic_pin'));*/
    
        $model = new UserModel();
        $contactmodel = new ContactModel();
    
        // 1. Initial lookup
        $user = $model->where('id', $user_id)->first();
    
        // 3. If User doesn't exist, Create them first
        if (!$user) {
            return $this->respond([
                'status' => 0,
                'user_data' => $user
            ]);
        }
    
        // 4. Now that we definitely have a $user, fetch contacts
        $contacts = $contactmodel->where('user_id', $user['id'])
                         ->select('contact_name, contact_phone') // Select both
                         ->get()
                         ->getResultArray();


        $user['emergency_contacts'] = $contacts;
        
        return $this->respond([
            'status' => 200,
            'user_data' => $user
        ]);
        
    }
    
    public function update_profile()
    {
        helper(['form']);
    
        $userId       = $this->request->getPost('user_id');
        $name         = $this->request->getPost('name');
        $user_pin     = $this->request->getPost('user_pin');
        $panic_pin    = $this->request->getPost('panic_pin');
        $contactsJson = $this->request->getPost('contacts');
    
        if (!$userId) {
            return $this->response->setJSON([
                'status' => false,
                'message' => 'User ID missing'
            ]);
        }
    
        // Decode contacts JSON into an associative array
        $contacts = [];
        if (!empty($contactsJson)) {
            $contacts = json_decode($contactsJson, true);
    
            if (json_last_error() !== JSON_ERROR_NONE) {
                return $this->response->setJSON([
                    'status' => false,
                    'message' => 'Invalid contacts JSON'
                ]);
            }
        }
    
        $db = \Config\Database::connect();
        $db->transStart();
    
        /** ✅ Always update users table */
        $db->table('users')
            ->where('id', $userId)
            ->update([
                'name'      => $name,
                'user_pin'  => $user_pin,
                'panic_pin' => $panic_pin,
            ]);
    
        $contactTable = $db->table('emergency_contacts');
    
        /** 🔹 Get existing contacts from DB to decide what to delete */
        $existingContacts = $contactTable
            ->where('user_id', $userId)
            ->get()
            ->getResultArray();
    
        $existingPhones = array_column($existingContacts, 'contact_phone');
    
        /** 🔹 Extract just the phones from the new incoming JSON objects for comparison */
        $newPhoneNumbers = [];
        foreach ($contacts as $c) {
            if (!empty($c['phone'])) {
                $newPhoneNumbers[] = $c['phone'];
            }
        }
    
        /** 🗑️ Delete removed contacts */
        foreach ($existingPhones as $oldPhone) {
            if (!in_array($oldPhone, $newPhoneNumbers)) {
                $contactTable
                    ->where('user_id', $userId)
                    ->where('contact_phone', $oldPhone)
                    ->delete();
            }
        }
    
        /** ➕ Insert or Update new contacts */
        foreach ($contacts as $contact) {
            $phone = $contact['phone'] ?? '';
            $cName = $contact['name'] ?? 'Unknown';
    
            if (empty($phone)) continue;
    
            $exists = $contactTable
                ->where('user_id', $userId)
                ->where('contact_phone', $phone)
                ->get()
                ->getRow();
    
            if ($exists) {
                // Update name and priority if contact exists
                $contactTable
                    ->where('id', $exists->id)
                    ->update([
                        'contact_name' => $cName,
                        'priority'     => 1
                    ]);
            } else {
                // Insert new record with both name and phone
                $contactTable->insert([
                    'user_id'       => $userId,
                    'contact_name'  => $cName,
                    'contact_phone' => $phone,
                    'priority'      => 1
                ]);
            }
        }
    
        $db->transComplete();
    
        if ($db->transStatus() === false) {
            return $this->response->setJSON([
                'status' => false,
                'message' => 'Database error during transaction'
            ]);
        }
    
        return $this->response->setJSON([
            'status' => true,
            'message' => 'Profile and Contacts updated successfully'
        ]);
    }

    public function update_contact(){
        $userId      = $this->request->getPost('user_id');
        $contactsJson = $this->request->getPost('contacts');
    
        if (!$userId) {
            return $this->response->setJSON([
                'status' => false,
                'message' => 'User ID missing'
            ]);
        }
    
        // Decode contacts JSON
        $contacts = [];
        if (!empty($contactsJson)) {
            $contacts = json_decode($contactsJson, true);
    
            if (json_last_error() !== JSON_ERROR_NONE) {
                return $this->response->setJSON([
                    'status' => false,
                    'message' => 'Invalid contacts JSON'
                ]);
            }
        }
    
        $db = \Config\Database::connect();
        $db->transStart();
    
        $contactTable = $db->table('emergency_contacts');
    
        $existingContacts = $contactTable
            ->where('user_id', $userId)
            ->get()
            ->getResultArray();
    
        $existingPhones = array_column($existingContacts, 'contact_phone');
    
        /**  Normalize incoming contacts */
        $newPhones = array_unique(array_filter($contacts));
    
        /**  Delete removed contacts */
        foreach ($existingPhones as $oldPhone) {
            if (!in_array($oldPhone, $newPhones)) {
                $contactTable
                    ->where('user_id', $userId)
                    ->where('contact_phone', $oldPhone)
                    ->delete();
            }
        }
    
        /**  Insert or Update new contacts */
        /*foreach ($newPhones as $phone) {
    
            $exists = $contactTable
                ->where('user_id', $userId)
                ->where('contact_phone', $phone)
                ->get()
                ->getRow();
    
            if ($exists) {
                // Update if needed (priority or timestamp etc.)
                $contactTable
                    ->where('id', $exists->id)
                    ->update([
                        'priority' => 1
                    ]);
            } else {
                // Insert new
                $contactTable->insert([
                    'user_id'       => $userId,
                    'contact_phone' => $phone,
                    'priority'      => 1
                ]);
            }
        }*/

        /** Insert or Update new contacts */
        foreach ($contacts as $contact) {
            $phone = $contact['phone'] ?? '';
            $name  = $contact['name'] ?? 'Unknown';
        
            if (empty($phone)) continue;
        
            $exists = $contactTable
                ->where('user_id', $userId)
                ->where('contact_phone', $phone)
                ->get()
                ->getRow();
        
            if ($exists) {
                $contactTable
                    ->where('id', $exists->id)
                    ->update([
                        'contact_name' => $name, // Now saving the name!
                        'priority'     => 1
                    ]);
            } else {
                $contactTable->insert([
                    'user_id'       => $userId,
                    'contact_name'  => $name, // Now saving the name!
                    'contact_phone' => $phone,
                    'priority'      => 1
                ]);
            }
        }

        $db->transComplete();
    
        if ($db->transStatus() === false) {
            return $this->response->setJSON([
                'status' => false,
                'message' => 'Database error'
            ]);
        }
    
        return $this->response->setJSON([
            'status' => true,
            'message' => 'Contact updated successfully'
        ]);        
    }
    
    public function upload_profile_image() {
        $userId = $this->request->getPost('user_id');
        $file = $this->request->getFile('profile_pic');
    
        if ($file->isValid() && !$file->hasMoved()) {
            $newName = $file->getRandomName();
            //$file->move(WRITEPATH . 'uploads/profiles', $newName);
            $file->move(ROOTPATH . 'public/uploads/profiles', $newName);
            
            $db = \Config\Database::connect();
            $db->table('users')->where('id', $userId)->update([
                'profile_image' => $newName
            ]);
    
            return $this->response->setJSON(['status' => 1, 'message' => 'Uploaded']);
        }
    }
    
}