<?php
include 'config.php';
// Koneksi Database
$koneksi = mysqli_connect($dbhost,$dbuser,$dbpassword,$dbname);

$cektable = mysqli_query($koneksi, "SELECT * FROM users_id" );
$hasildata = mysqli_fetch_assoc($cektable);

// Global fallback
$global_timezone = $hasildata['timezone'] ?? 'Asia/Jakarta';
date_default_timezone_set($global_timezone);

// We will refine this later in the script or in header.php after active_event_id is known.
// For now, let's just make sure it doesn't crash.
$timezone = $global_timezone;

function get_active_event_id() {
    global $koneksi;
    if (!isset($_SESSION['login'])) return null;
    
    $user_id = $_SESSION['id'];
    
    // 1. Check session first
    if (isset($_SESSION['active_event_id'])) {
        return $_SESSION['active_event_id'];
    }
    
    // 2. Check user's last active event in DB
    $res = mysqli_query($koneksi, "SELECT active_event_id FROM users_id WHERE id = '$user_id'");
    $data = mysqli_fetch_assoc($res);
    
    if ($data['active_event_id']) {
        $_SESSION['active_event_id'] = $data['active_event_id'];
        return $data['active_event_id'];
    }
    
    // 3. Fallback to first available event assigned to user
    $res = mysqli_query($koneksi, "SELECT event_id FROM user_events WHERE user_id = '$user_id' LIMIT 1");
    $data = mysqli_fetch_assoc($res);
    
    if ($data['event_id']) {
        $_SESSION['active_event_id'] = $data['event_id'];
        mysqli_query($koneksi, "UPDATE users_id SET active_event_id = '".$data['event_id']."' WHERE id = '$user_id'");
        return $data['event_id'];
    }
    
    return null;
}

function is_subscription_active($user_id) {
    global $koneksi;
    $res = mysqli_query($koneksi, "SELECT role, subscription_period, expiry_date FROM users_id WHERE id = '$user_id'");
    $data = mysqli_fetch_assoc($res);
    
    // Admins always active
    if ($data['role'] == 'admin') return true;
    
    // Check if subscription is set to active
    if ($data['subscription_period'] == 'Tidak Aktif') return false;
    
    // Check if expired
    if ($data['expiry_date']) {
        $expiry = strtotime($data['expiry_date']);
        $now = time();
        if ($now > $expiry) return false;
    } else {
        // If period is NOT 'Tidak Aktif' but no expiry date, assume inactive for safety
        return false;
    }
    
    return true;
}

function calculate_expiry($period, $start_date = null) {
    if ($period == 'Tidak Aktif') return null;
    
    $start = $start_date ? strtotime($start_date) : time();
    $interval = '';
    
    switch ($period) {
        case '1 Minggu': $interval = '+7 days'; break;
        case '1 Bulan': $interval = '+1 month'; break;
        case '3 Bulan': $interval = '+3 months'; break;
        case '6 Bulan': $interval = '+6 months'; break;
        case '12 Bulan': $interval = '+12 months'; break;
        default: return null;
    }
    
    return date('Y-m-d H:i:s', strtotime($interval, $start));
}


function tanggal_indo($tanggal, $cetak_hari = true)
{
	$hari = array ( 1 =>    'Senin',
				'Selasa',
				'Rabu',
				'Kamis',
				'Jumat',
				'Sabtu',
				'Minggu'
			);
			
	$bulan = array (1 =>   'Januari',
				'Februari',
				'Maret',
				'April',
				'Mei',
				'Juni',
				'Juli',
				'Agustus',
				'September',
				'Oktober',
				'November',
				'Desember'
			);
	$split 	  = explode('-', $tanggal);
	$tgl_indo = $split[2] . ' ' . $bulan[ (int)$split[1] ] . ' ' . $split[0];
	
	if ($cetak_hari) {
		$num = date('N', strtotime($tanggal));
		return $hari[$num] . ' ' . $tgl_indo;
	}
	return $tgl_indo;
}

function get_cat(){
    global $koneksi;
    $event_id = get_active_event_id();
    if (!$event_id) return [];

    $result = mysqli_query($koneksi, "SELECT * FROM categories WHERE event_id = '$event_id'" );
    $rows = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $rows[] = $row;
    }
    return $rows;
}

function get_all_events() {
    global $koneksi;
    return query("SELECT * FROM event_id ORDER BY acara ASC");
}

function get_user_event_ids($user_id) {
    global $koneksi;
    $res = mysqli_query($koneksi, "SELECT event_id FROM user_events WHERE user_id = '$user_id'");
    $ids = [];
    while ($row = mysqli_fetch_assoc($res)) {
        $ids[] = $row['event_id'];
    }
    return $ids;
}

function linHome(){
    if(isset($_SERVER['HTTPS'])){
        $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
    }
    else{
        $protocol = 'http';
    }
    return $protocol . "://" . $_SERVER["SERVER_NAME"];
}

// send notif wa onesender
function OneSender($apikey, $apiurl, $pesan, $phone) {
    global $pesan;
	$phone = preg_replace('/^8/','08', $phone);
	$phone = preg_replace('/[^0-9]/', '', $phone);
	$phone = preg_replace('/^620/','62', $phone);
	$phone = preg_replace('/^0/','62', $phone);
    $data = array( 
        'recipient_type' => 'individual',
        'to' => $phone,
        'type' => 'text',
        'text' => array(
            'body' => $pesan
        )
    ); 
    
    $json_data = json_encode($data);
    $headers = [
          'Content-Type: application/json',
            'Authorization: Bearer '.$apikey
    ];
            
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiurl);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $response = curl_exec($ch);
    $header = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    // echo $response;
}

// send notif wa starsender
function Starsender($apikey, $pesan, $phone) {
    global $pesan;
	$phone = preg_replace('/^8/','08', $phone);
	$phone = preg_replace('/[^0-9]/', '', $phone);
	$phone = preg_replace('/^620/','62', $phone);
	$phone = preg_replace('/^0/','62', $phone);
    $curl = curl_init();
    curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://starsender.online/api/sendText?message='.rawurlencode($pesan).'&tujuan='.rawurlencode($phone.'@s.whatsapp.net'),
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'POST',
      CURLOPT_HTTPHEADER => array(
        'apikey: '.$apikey
      ),
    ));
    
    $response = curl_exec($curl);
    curl_close($curl);
    // echo $response;
}

function randomString($number)
{
    $str = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV";
    $str = str_shuffle($str);
    $str = substr($str, 0, $number);
    return $str;
}

function sendemail($host,$port,$username,$password,$encryp,$emailweb,$nameweb,$title,$email,$name,$body) {
    include "smtp/class.phpmailer.php";
    $mail = new PHPMailer; 
    $mail->IsSMTP();
    $mail->SMTPSecure = $encryp; 
    $mail->Host = $host; //host masing2 provider email
    $mail->SMTPDebug = 0;
    $mail->Port = $port;
    $mail->SMTPAuth = true;
    $mail->Username = $username; //user email
    $mail->Password = $password; //password email 
    $mail->SetFrom($emailweb,$nameweb); //set email pengirim
    $mail->Subject = $title; //subyek email
    $mail->AddAddress($email,$name);  //tujuan email
    $mail->MsgHTML($body);
    $mail->Body = $body;
    if($mail->Send());
    // echo "Message has been sent";
    // else echo "Failed to sending message";
} 

// Membuat fungsi update
function user_update($data)
{
    global $koneksi;
    
    $id = htmlspecialchars($data['id']);
     
    $nama = htmlspecialchars($data['username']);

    $tgl = htmlspecialchars($data['register_date']);
    
    $password = htmlspecialchars($data['password']);
    
    $newpass = md5($password);

    $sql = "UPDATE `users_id` SET password='$newpass' WHERE id='".$id."'";

    mysqli_query($koneksi, $sql);

    return mysqli_affected_rows($koneksi);
    
}

// Membuat fungsi update
function user_update_admin($data)
{
    global $koneksi;
    
    $id = htmlspecialchars($data['id']);
    $nama = htmlspecialchars($data['username']);
    $newpass = htmlspecialchars($data['password']);
    $hashpass = md5($newpass);
    $phone = htmlspecialchars($data['phone']);
    $role = htmlspecialchars($data['role']);
    $email = htmlspecialchars($data['email']);
    
    $period = htmlspecialchars($data['subscription_period'] ?? 'Tidak Aktif');
    $expiry = calculate_expiry($period);

    if(!empty($newpass)){
         $sql = "UPDATE `users_id` SET username='$nama', email='$email', phone='$phone', role='$role', password='$hashpass', subscription_period='$period', expiry_date=".($expiry ? "'$expiry'" : "NULL")." WHERE id='".$id."'";
    }else{
        $sql = "UPDATE `users_id` SET username='$nama', email='$email', role='$role', phone='$phone', subscription_period='$period', expiry_date=".($expiry ? "'$expiry'" : "NULL")." WHERE id='".$id."'";
    }
    
    mysqli_query($koneksi, $sql);

    // Sync Events
    mysqli_query($koneksi, "DELETE FROM user_events WHERE user_id = '$id'");
    if (isset($data['events']) && is_array($data['events'])) {
        foreach ($data['events'] as $event_id) {
            $event_id = (int)$event_id;
            mysqli_query($koneksi, "INSERT IGNORE INTO user_events (user_id, event_id) VALUES ('$id', '$event_id')");
        }
    }

    return mysqli_affected_rows($koneksi);
}

// Membuat fungsi hapus
function user_del($id)
{
    global $koneksi;

    mysqli_query($koneksi, "DELETE FROM users_id WHERE id = $id");
    return mysqli_affected_rows($koneksi);
}

// Membuat fungsi tambah user
function add_user($data)
{
    global $koneksi;
    
    $nama = htmlspecialchars($data['username']);
    $email = htmlspecialchars($data['email']);
    $phone = htmlspecialchars($data['phone']);
    $tgl = date('Y-m-d H:i:s');
    $password = 'user123';
    $newpass = md5($password);
    $role = htmlspecialchars($data['role']);
    $period = htmlspecialchars($data['subscription_period'] ?? 'Tidak Aktif');
    $expiry = calculate_expiry($period);
    
    $sql = "INSERT INTO users_id (username, email, phone, register_date, role, password, subscription_period, expiry_date) values ('$nama', '$email', '$phone', '$tgl', '$role', '$newpass', '$period', ".($expiry ? "'$expiry'" : "NULL").")";
    mysqli_query($koneksi, $sql);
    $user_id = mysqli_insert_id($koneksi);

    // Sync Events
    if (isset($data['events']) && is_array($data['events'])) {
        foreach ($data['events'] as $event_id) {
            $event_id = (int)$event_id;
            mysqli_query($koneksi, "INSERT IGNORE INTO user_events (user_id, event_id) VALUES ('$user_id', '$event_id')");
        }
    }

    return mysqli_affected_rows($koneksi);
}

// membuat fungsi query dalam bentuk array
function query($query)
{
    // Koneksi database
    global $koneksi;

    $result = mysqli_query($koneksi, $query);
    if (!$result) return [];

    // membuat varibale array
    $rows = [];

    // mengambil semua data dalam bentuk array
    while ($row = mysqli_fetch_assoc($result)) {
        $rows[] = $row;
    }

    return $rows;
}

// Membuat fungsi update
function update($data)
{
    global $koneksi;
    $event_id = get_active_event_id();
    if (!$event_id) return 0;
    
    $id = htmlspecialchars($data['no_id']);
    $nama = htmlspecialchars($data['nama']);
    $tgl = htmlspecialchars($data['tgl']);
    $jam = htmlspecialchars($data['jam']);
    $tamu = htmlspecialchars($data['tamu']);
    $whatsapp = htmlspecialchars($data['whatsapp']);
    $jumlah_tamu = isset($data['jumlah_tamu']) ? (int)$data['jumlah_tamu'] : 1;

    $sql = "UPDATE `comment_id` SET nama='$nama', tgl='$tgl', jam='$jam', tamu='$tamu', whatsapp='$whatsapp', jumlah_tamu='$jumlah_tamu' WHERE no_id='".$id."' AND event_id = '$event_id'";

    mysqli_query($koneksi, $sql);

    return mysqli_affected_rows($koneksi);
}

// Membuat fungsi tambah
function tambah($data)
{
    global $koneksi;
    $event_id = get_active_event_id();
    if (!$event_id) return 0;
    
    $nama = htmlspecialchars($data['nama']);
    $tamu = htmlspecialchars($data['tamu']);
    $tgl = date('d-m-Y');
    $jam = date('H:i');
    $whatsapp = htmlspecialchars($data['whatsapp']);
    $jumlah_tamu = isset($data['jumlah_tamu']) ? (int)$data['jumlah_tamu'] : 1;

    $sql = "INSERT INTO `comment_id` (`nama`,`tgl`,`jam`, `tamu`, `whatsapp`, `event_id`, `jumlah_tamu`) VALUES ('$nama', '$tgl', '$jam', '$tamu', '$whatsapp', '$event_id', '$jumlah_tamu')";

    mysqli_query($koneksi, $sql);

    return mysqli_affected_rows($koneksi);
}

// Membuat fungsi hapus
function hapus($no_id)
{
    global $koneksi;
    $event_id = get_active_event_id();
    if (!$event_id) return 0;

    mysqli_query($koneksi, "DELETE FROM comment_id WHERE no_id = $no_id AND event_id = '$event_id'");
    return mysqli_affected_rows($koneksi);
}


// Membuat fungsi hapus
function hapuscat($id)
{
    global $koneksi;

    mysqli_query($koneksi, "DELETE FROM categories WHERE id = $id");
    return mysqli_affected_rows($koneksi);
}

function redirect ($path = "/") 
{
  header("location: $path");
  exit;
}


function url ($path = "")
{
    if ($path !== "") $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    else $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    
    $validURL = str_replace("&", "&amp;", $url);
    
    return $validURL;
}

function api_curl_connect( $api_url ){
	$connection_c = curl_init(); // initializing
	curl_setopt( $connection_c, CURLOPT_URL, $api_url ); // API URL to connect
	curl_setopt( $connection_c, CURLOPT_RETURNTRANSFER, 1 ); // return the result, do not print
	curl_setopt( $connection_c, CURLOPT_TIMEOUT, 20 );
	$json_return = curl_exec( $connection_c ); // connect and get json data
	curl_close( $connection_c ); // close connection
	return json_decode( $json_return ); // decode and return
}