<?php
// =============================================
// SHARK CRM - Database Connection
// =============================================

define('DB_HOST', 'localhost');
define('DB_USER', 'amctagme_user');
define('DB_PASS', 'tag.amc.2013');
define('DB_NAME', 'amctagme_shark_crm');

// App configuration
require_once __DIR__ . '/config/app.php';

// Upload configuration
define('UPLOAD_DIR', __DIR__ . '/uploads/');
define('UPLOAD_URL', './uploads/');

$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

if ($conn->connect_error) {
    die(json_encode(['success' => false, 'message' => 'Database connection failed: ' . $conn->connect_error]));
}

$conn->set_charset('utf8mb4');

// Create uploads directory if not exists
if (!is_dir(UPLOAD_DIR)) {
    mkdir(UPLOAD_DIR, 0755, true);
}

function sanitize($conn, $data) {
    return $conn->real_escape_string(trim($data));
}

function jsonResponse($success, $message = '', $data = []) {
    header('Content-Type: application/json');
    echo json_encode(array_merge(['success' => $success, 'message' => $message], $data));
    exit;
}

function formatDate($dt) {
    if (!$dt) return 'N/A';
    return date('M d, Y', strtotime($dt));
}

function formatDateTime($dt) {
    if (!$dt) return 'N/A';
    return date('M d, Y H:i', strtotime($dt));
}

function renderStars($priority, $max = 5) {
    $html = '';
    for ($i = 1; $i <= $max; $i++) {
        $class = $i <= $priority ? 'star filled' : 'star';
        $html .= '<span class="' . $class . '">★</span>';
    }
    return $html;
}

function getUserUploadPath() {
    session_start();
    $user_id = $_SESSION['user_id'] ?? 0;
    $path = rtrim(UPLOAD_DIR, '/\\') . DIRECTORY_SEPARATOR . 'user_' . $user_id . DIRECTORY_SEPARATOR;
    if (!is_dir($path)) {
        mkdir($path, 0755, true);
    }
    return $path;
}

function getUserUploadUrl() {
    session_start();
    $user_id = $_SESSION['user_id'] ?? 0;
    return UPLOAD_URL . 'user_' . $user_id . '/';
}

// ---- Permissions / schema-safe helpers ----
function tableExists($conn, $table) {
    $table = $conn->real_escape_string($table);
    $res = $conn->query("SHOW TABLES LIKE '$table'");
    return $res && $res->num_rows > 0;
}
function columnExists($conn, $table, $column) {
    $table = $conn->real_escape_string($table);
    $column = $conn->real_escape_string($column);
    $res = $conn->query("SHOW COLUMNS FROM `$table` LIKE '$column'");
    return $res && $res->num_rows > 0;
}
function crmPagesConfig() {
    $file = __DIR__ . '/config/pages.php';
    return file_exists($file) ? include $file : [];
}
function currentUserRow($conn, $user_id=null) {
    $uid = $user_id ? (int)$user_id : (int)($_SESSION['user_id'] ?? 0);
    if (!$uid) return null;
    $q = $conn->query("SELECT u.*, r.name role_name, r.permissions role_permissions FROM users u LEFT JOIN roles r ON u.role_id=r.id WHERE u.id=$uid LIMIT 1");
    return ($q && $q->num_rows) ? $q->fetch_assoc() : null;
}
function currentUserIsSuperAdmin($conn, $user_id=null) {
    $u = currentUserRow($conn, $user_id);
    if (!$u) return false;
    if (array_key_exists('is_super_admin', $u) && (int)$u['is_super_admin'] === 1) return true;
    return (int)($u['id'] ?? 0) === 1; // backward compatibility for the first big admin
}
function currentUserIsAccountOwner($conn, $user_id=null) {
    $u = currentUserRow($conn, $user_id);
    if (!$u) return false;
    if (array_key_exists('is_account_owner', $u) && (int)$u['is_account_owner'] === 1) return true;
    $perm = json_decode($u['role_permissions'] ?? '', true);
    return (int)($u['role_id'] ?? 0) === 1 || (!empty($perm['all']));
}
function currentUserIsAdmin($conn) {
    return currentUserIsSuperAdmin($conn) || currentUserIsAccountOwner($conn);
}

function crmPermissionAlias($page) {
    $aliases = [
        'lead' => 'leads',
        'customer' => 'customers',
        'customer_view' => 'customers',
        'add_customer' => 'customers',
        'edit_customer' => 'customers',
        'quotation' => 'quotations',
        'quotation_view' => 'quotations',
        'quotation_invoice' => 'quotations',
        'audience_add' => 'audience',
        'audience_edit' => 'audience',
        'audience_view' => 'audience',
        'campaign_add' => 'campaigns',
        'campaign_edit' => 'campaigns',
        'campaign_view' => 'campaigns',
    ];
    return $aliases[$page] ?? $page;
}
function userCan($conn, $page, $action='view', $user_id=null) {
    $page = crmPermissionAlias($page);
    $user_id = $user_id ? (int)$user_id : (int)($_SESSION['user_id'] ?? 0);
    $account_id = (int)($_SESSION['account_id'] ?? 0);
    if (!$user_id || !$account_id) return false;

    // Big admin and account owner always have full access inside their account.
    if (currentUserIsSuperAdmin($conn, $user_id) || currentUserIsAccountOwner($conn, $user_id)) return true;

    if (!tableExists($conn, 'user_permissions')) return false;
    $page = $conn->real_escape_string($page);
    $action = $conn->real_escape_string($action);
    $q = $conn->query("SELECT allowed FROM user_permissions WHERE account_id=$account_id AND user_id=$user_id AND page_key='$page' AND action_key='$action' LIMIT 1");
    return $q && $q->num_rows && (int)$q->fetch_assoc()['allowed'] === 1;
}
function requirePermission($conn, $page, $action='view') {
    if (!userCan($conn, $page, $action)) jsonResponse(false, 'Permission denied');
}
function pageAllowed($conn, $page) { return userCan($conn, crmPermissionAlias($page), 'view'); }
function grantFullPermissions($conn, $account_id, $user_id) {
    $account_id=(int)$account_id; $user_id=(int)$user_id;
    if (!tableExists($conn, 'user_permissions')) return;
    $conn->query("DELETE FROM user_permissions WHERE account_id=$account_id AND user_id=$user_id");
    $pages = crmPagesConfig();
    $stmt = $conn->prepare("INSERT INTO user_permissions (account_id,user_id,page_key,action_key,allowed) VALUES (?,?,?,?,1)");
    foreach ($pages as $pageKey=>$cfg) {
        foreach (($cfg['actions'] ?? ['view']) as $actionKey) {
            $stmt->bind_param('iiss', $account_id, $user_id, $pageKey, $actionKey);
            $stmt->execute();
        }
    }
}
function createDefaultStages($conn, $account_id) {
    $account_id=(int)$account_id;
    if (!tableExists($conn, 'stage')) return;
    $exists=$conn->query("SELECT id FROM stage WHERE account_id=$account_id LIMIT 1");
    if ($exists && $exists->num_rows) return;
    $defaults = [
        ['New',1,'#00e5c3',1,0],
        ['In progress',2,'#f59e0b',0,0],
        ['Won',3,'#10b981',0,1],
        ['Lost',4,'#ef4444',0,1],
    ];
    $stmt=$conn->prepare("INSERT INTO stage (name,position,color,is_start,is_end,account_id) VALUES (?,?,?,?,?,?)");
    foreach($defaults as $d){ $stmt->bind_param('sisiii',$d[0],$d[1],$d[2],$d[3],$d[4],$account_id); $stmt->execute(); }
}
