<?php

function current_customer($refresh = false)
{
    static $customer = false;
    if ($customer === false || $refresh) {
        $id = sess('customer_id');
        $customer = $id ? db_find('customers', $id) : null;
        if ($id && !$customer) {
            sess_forget('customer_id');
        }
    }
    return $customer;
}

function is_customer()
{
    return current_customer() !== null;
}

function customer_id()
{
    return is_customer() ? (int) current_customer()['id'] : null;
}

function customer_guard()
{
    if (in_admin() || !in_array(current_file(), CUSTOMER_PAGES, true) || is_customer()) {
        return;
    }
    sess_set('after_login', request_uri());
    flash('Devam etmek için giriş yapın.', 'error');
    go(url('giris'));
}

function customer_login($email, $password)
{
    if (login_locked('customer')) {
        return false;
    }
    $customer = db_one('SELECT * FROM customers WHERE email = ?', [$email]);
    if (!$customer || !password_verify($password, $customer['password'])) {
        login_failed('customer');
        return false;
    }
    login_clear('customer');
    sess_renew();
    sess_set('customer_id', $customer['id']);
    current_customer(true);
    favorite_merge();
    return true;
}

function customer_register($data)
{
    $id = db_insert('customers', [
        'name'     => $data['name'],
        'email'    => $data['email'],
        'phone'    => $data['phone'],
        'password' => password_hash($data['password'], PASSWORD_DEFAULT),
    ]);
    sess_renew();
    sess_set('customer_id', $id);
    current_customer(true);
    favorite_merge();
    send_template('welcome', $data['email'], ['ad' => $data['name']]);
    return $id;
}

function customer_logout()
{
    sess_forget('customer_id');
    sess_renew();
    current_customer(true);
}

function email_taken($email, $ignore_id = 0)
{
    return (bool) db_value('SELECT COUNT(*) FROM customers WHERE email = ? AND id != ?', [$email, $ignore_id]);
}

function after_login_url()
{
    $url = safe_url(sess('after_login', ''), url('hesabim'));
    sess_forget('after_login');
    return $url;
}

function account_menu()
{
    return [
        ['hesabim',      'Hesap bilgilerim', 'user'],
        ['siparislerim', 'Siparişlerim',     'bag'],
        ['favorilerim',  'Favorilerim',      'heart'],
    ];
}
