<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * @property CI_DB $db
 * @property CI_Output $output
 */
class Profile extends CI_Controller {

    private $tableUser = 'users';

    public function __construct() {
        parent::__construct();
        $this->load->database();
        $this->output->set_content_type('application/json');
    }



    public function getnomor($id = null) {
    $user = $this->db->get_where($this->tableUser, ['id_user' => $id])->row();

    if (!$user) {
        echo json_encode([
            'status' => false,
            'message' => 'Data tidak ditemukan',
            'data' => null
        ]);
    } else {
        // WAJIB dibungkus dalam array seperti ini
        echo json_encode([
            'status' => true,
            'message' => 'Berhasil mengambil data',
            'data' => $user 
        ]);
    }
}
    /**
     * GET /api/profile/get/{id}
     */
    public function get($id = null) {
        if (!$id) {
            echo json_encode([
                'status' => false,
                'message' => 'ID user tidak diberikan'
            ]);
            return;
        }

        $user = $this->db
            ->get_where($this->tableUser, ['id_user' => $id])
            ->row();

        if (!$user) {
            echo json_encode([
                'status' => false,
                'message' => 'Data user tidak ditemukan'
            ]);
            return;
        }

        echo json_encode($user);
    }

    /**
     * PUT /api/profile/update/{id}
     */
    public function update($id = null) {
        if (!$id) {
            echo json_encode([
                'status' => false,
                'message' => 'ID user tidak diberikan'
            ]);
            return;
        }

        $rawInput = file_get_contents('php://input');
        $data = json_decode($rawInput, true);

        if (!$data) {
            echo json_encode([
                'status' => false,
                'message' => 'JSON kosong atau tidak valid'
            ]);
            return;
        }

        $updateData = [
            'username'  => trim($data['username'] ?? ''),
            'full_name' => trim($data['full_name'] ?? ''),
            'telepon'   => trim($data['telepon'] ?? ''),
            'email'     => trim($data['email'] ?? ''),
            'alamat'    => trim($data['alamat'] ?? '')
        ];

        if (empty($updateData['username']) || empty($updateData['full_name'])) {
            echo json_encode([
                'status' => false,
                'message' => 'Username & Full Name wajib diisi'
            ]);
            return;
        }

        $this->db->where('id_user', $id);
        $updated = $this->db->update($this->tableUser, $updateData);

        echo json_encode([
            'status'  => $updated,
            'message' => $updated ? 'Profil berhasil diperbarui' : 'Gagal memperbarui profil'
        ]);
    }
}
