<?php
// backend/config/database.php
class Database {
    private $host = "localhost";
    private $db_name = "resume_builder";
    private $username = "root";
    private $password = "";
    public $conn;

    public function getConnection() {
        $this->conn = null;
        try {
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, 
                                  $this->username, $this->password);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $e) {
            echo "Connection error: " . $e->getMessage();
        }
        return $this->conn;
    }
}
?>

<?php
// backend/api/save_resume.php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");

require_once "../config/database.php";

session_start();
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(["error" => "Unauthorized"]);
    exit;
}

$database = new Database();
$db = $database->getConnection();

$data = json_decode(file_get_contents("php://input"), true);

$query = "INSERT INTO resumes (user_id, title, template, sections_order, data) 
          VALUES (:user_id, :title, :template, :sections_order, :data)
          ON DUPLICATE KEY UPDATE 
          title = :title, template = :template, 
          sections_order = :sections_order, data = :data";

$stmt = $db->prepare($query);

$stmt->bindParam(":user_id", $_SESSION['user_id']);
$stmt->bindParam(":title", $data['title']);
$stmt->bindParam(":template", $data['template']);
$stmt->bindParam(":sections_order", json_encode($data['sections_order']));
$stmt->bindParam(":data", json_encode($data['data']));

if ($stmt->execute()) {
    echo json_encode(["success" => true, "id" => $db->lastInsertId()]);
} else {
    http_response_code(500);
    echo json_encode(["error" => "Failed to save resume"]);
}
?>