<?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');

// Upload configuration
define('UPLOAD_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 = UPLOAD_DIR . 'user_' . $user_id . '/';
    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 currentUserIsAdmin($conn) {
    $uid = (int)($_SESSION['user_id'] ?? 0);
    if (!$uid) return false;
    $q = $conn->query("SELECT r.permissions, r.id role_id FROM users u LEFT JOIN roles r ON u.role_id=r.id WHERE u.id=$uid LIMIT 1");
    if (!$q || !$q->num_rows) return false;
    $r = $q->fetch_assoc();
    $perm = json_decode($r['permissions'] ?? '', true);
    return (int)$r['role_id'] === 1 || (!empty($perm['all']));
}
function userCan($conn, $page, $action='view', $user_id=null) {
    $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;
    if (currentUserIsAdmin($conn)) return true;
    if (!tableExists($conn, 'user_permissions')) return true;
    $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, $page, 'view'); }
