<?php
// Database configuration
define('DB_HOST', 'localhost');
define('DB_USER', 'krishivkkulgam_agri_advisor_user'); // Your agri advisor username
define('DB_PASS', '8XlQ!pT}2rXstjtd'); // Your agri advisor password
define('DB_NAME', 'krishivkkulgam_agri_advisor'); // Your agri advisor database name

// Application configuration
define('APP_NAME', 'SKUAST-K Degree Certificate Portal');
define('APP_URL', 'http://localhost/degree_portal');
define('UPLOAD_PATH', __DIR__ . '/uploads/');
define('ALLOWED_DOMAINS', ['skuastkashmir.ac.in']);

// Create upload directory if not exists
if (!file_exists(UPLOAD_PATH)) {
    mkdir(UPLOAD_PATH, 0777, true);
}

// Session configuration - ONLY set if session is not already active
if (session_status() === PHP_SESSION_NONE) {
    // Set session settings BEFORE starting session
    ini_set('session.cookie_httponly', 1);
    ini_set('session.use_only_cookies', 1);
    session_start();
}

// Database connection function
function getDB() {
    try {
        $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        return $pdo;
    } catch(PDOException $e) {
        die("Database connection failed: " . $e->getMessage());
    }
}

// Security functions
function sanitize($input) {
    return htmlspecialchars(strip_tags(trim($input)));
}

function validateEmail($email) {
    $domain = substr(strrchr($email, "@"), 1);
    return in_array($domain, ALLOWED_DOMAINS);
}

function generateCertificateNo() {
    return 'SKUAST-' . date('Y') . '-' . str_pad(rand(1, 99999), 5, '0', STR_PAD_LEFT);
}

function logActivity($certificate_id, $action, $user_id) {
    $pdo = getDB();
    $stmt = $pdo->prepare("INSERT INTO certificate_logs (certificate_id, action, user_id, ip_address) VALUES (?, ?, ?, ?)");
    $stmt->execute([$certificate_id, $action, $user_id, $_SERVER['REMOTE_ADDR']]);
}

// Check if user is logged in (to be used in protected pages)
function checkLogin() {
    if (!isset($_SESSION['user_id'])) {
        header('Location: index.php');
        exit();
    }
}
?>